(→Importing math) |
(→User interfaces) |
||

(31 intermediate revisions by the same user not shown) | |||

Line 1: | Line 1: | ||

− | This page contains examples and links to programs used for our Research Methods - Programming with Python short course. | + | This page contains examples and links to programs used for our [http://prancer.physics.louisville.edu/astrowiki/index.php/Python_for_Physics_and_Astronomy Research Methods - Programming with Python short course.] |

== Very simple Python == | == Very simple Python == | ||

Line 5: | Line 5: | ||

Start a Python interactive session using the "python" command to get a >>> prompt. | Start a Python interactive session using the "python" command to get a >>> prompt. | ||

− | === Command line | + | === Command line use === |

+ | |||

+ | There are many built-in features of Python that are described in the [http://docs.python.org/2/library/index.html documentation], but to get started let's do something very easy. | ||

Type | Type | ||

Line 100: | Line 102: | ||

3.1415926535897936 | 3.1415926535897936 | ||

− | The comprehensive list of math functions is on the [http://docs.python.org/2/library/math.html Python documentation site]. | + | The comprehensive list of math functions is on the [http://docs.python.org/2/library/math.html Python documentation site]. You can try out some of the more exotic possibilities on your own. |

+ | |||

+ | === Writing an executable program === | ||

+ | |||

+ | Let's turn off the real-time version of Python if you have it running by typing | ||

+ | |||

+ | exit() | ||

+ | |||

+ | or simply the combination of "ctrl" and "d"keys "ctrl+d" to return to the system prompt. | ||

+ | |||

+ | Select your favorite Python editor, and create a file we'll call test.py . If you have the Python interpreter associated with a .py extension, then when you click on a this file in a graphical user interface (regardless of the operating system) it will run "python test.py" and give you the result of the program in the file. Alternatively, in Linux or MacOS, if the first line of the file is | ||

+ | |||

+ | #!/usr/bin/python | ||

+ | |||

+ | this will tell the user interface to run python followed by the code that is in the file (assuming that the executable "python" program is in /usr/bin. Here is how you would write a "Hello World" program in python: | ||

+ | |||

+ | #!/usr/bin/python | ||

+ | print "Hello World!\n" | ||

+ | exit() | ||

+ | |||

+ | Hint here: the "\n" is a line feed that will create a blank line after printing the | ||

+ | text. | ||

+ | |||

+ | Now to run this program in MacOS or Linux you would make sure it's executable | ||

+ | |||

+ | ls -l test.py | ||

+ | |||

+ | returns | ||

+ | |||

+ | -rwxr-xr-x 1 john users 48 Feb 7 02:16 test.py | ||

+ | |||

+ | which tells me that I own the program and that I can execute it (The letters in groups in the listing of the program give the permissions, and the "x" means execute, "r" means read, and "w" means write. The first three are for the user who owns the file, the second three are for the group that use belongs to, and the last three are for everybody else.) With that, I can simply type | ||

+ | |||

+ | ./test.py | ||

+ | |||

+ | which means "run the program in this directory called test.py". The prefatory "./" is not needed if the PATH includes the current directory. Obviously there are operating system nuances here that have nothing in particular to do with Python, but have to be mastered to use the computer to its fullest. Alternatively on any system you can explictly ask for the python program | ||

+ | |||

+ | python test.py | ||

+ | |||

+ | which will take "test.py" as input and run it. In either case, you will see | ||

+ | |||

+ | Hello World! | ||

+ | |||

+ | |||

+ | == Elements of Python programming == | ||

+ | |||

+ | This is a an example of a Python program that asks for a value, calculates a result, and displays it for the user. The source code is available [http://prancer.physics.louisville.edu/classes/650/python/examples/ here] in the file ''trig.example'' . Down load by right clicking and saving the file locally with the extension ''.py'' rather than ''.example''. | ||

+ | |||

+ | #!/usr/bin/python | ||

+ | |||

+ | import math | ||

+ | |||

+ | # Print something for the user | ||

+ | |||

+ | print 'I will find trigometric functions for an angle.\n' | ||

+ | |||

+ | |||

+ | # Ask for a value for the angle | ||

+ | |||

+ | angle = raw_input('What is the angle in degrees? >> ') | ||

+ | |||

+ | # Convert the angle from degrees to radians and to the math | ||

+ | |||

+ | a = float(angle) | ||

+ | arad = math.radians(a) | ||

+ | sine = math.sin(arad) | ||

+ | cosine = math.cos(arad) | ||

+ | tangent = math.tan(arad) | ||

+ | |||

+ | # Output the results | ||

+ | |||

+ | print '\n' | ||

+ | print 'Radians: ', arad | ||

+ | print 'Sine: ', sine | ||

+ | print 'Cosine: ', cosine | ||

+ | print 'Tangent: ', tangent | ||

+ | print '\n' | ||

+ | |||

+ | # Exit nicely | ||

+ | |||

+ | exit() | ||

+ | |||

+ | == Solving problems with Python == | ||

+ | |||

+ | Suppose that we have a catalog of data containing information about astronomical objects, and we want to find the data in the catalog that are specifically for one entry, given my name. A typical use would be on the command line when that's possible, or by reading the name from another file. For this purpose we'll take the catalog called ''ngc2000.dat'' which contains all NGC and IC objects, read it, and find the one item we want. | ||

+ | |||

+ | A program illustrating the ideas we have discussed so far is available [http://prancer.physics.louisville.edu/classes/650/python/examples here]. Look for ngc_reader.example and download it with a right click. The data file ngc2000.dat is also there. | ||

+ | |||

+ | The reader will look for this catalog in the same directory it is executing, and will expect an NGC or IC number on the command line. If your operating system does not handle command line input, try it with the number assigned as text within the program body, and delete the code that reads the command line. | ||

+ | |||

+ | == Graphics with Python == | ||

+ | |||

+ | Programs illustrating how to do simple 2D plotting that we discussed here are available [http://prancer.physics.louisville.edu/classes/650/python/examples here]. Look for | ||

+ | |||

+ | *damped_cos.example | ||

+ | *two_plots.example | ||

+ | *two_overplots.example. | ||

+ | |||

+ | |||

+ | We have also copied a selection of the 3D plotting examples from matplotlib's source code to [http://prancer.physics.louisville.edu/classes/650/python/examples our server]: | ||

+ | |||

+ | *contour3d_demo3.example | ||

+ | *rotate_axes3d_demo.example | ||

+ | *subplot3d_demo.example | ||

+ | *surface3d_demo2.example | ||

+ | *surface3d_demo.example | ||

+ | *trisurf3d_demo.example | ||

+ | |||

+ | You will also find with additional information in matplotlib's [http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html 3D tutorial]. | ||

+ | |||

+ | == NumPy and SciPy == | ||

+ | |||

+ | Building on the damped_cos.example for plotting, the program numpy_fft.example [http://prancer.physics.louisville.edu/classes/650/python/examples on our server] will make an interactive plot of the Fourier transform using NumPy's FFT routines. It also illustrates how to create and use NumPy arrays, rather than explicitly calculating lists element by element. | ||

+ | |||

+ | Other examples illustrate SciPy fitting, interpolation, integration and statistics: | ||

+ | |||

+ | *curve_fit_plot.example | ||

+ | *integrate_function_plot.example | ||

+ | *integrate_numerical_plot.example | ||

+ | *interpolate_noisy_plot.example | ||

+ | *interpolate_plot.example | ||

+ | *norm_probability_plot.example | ||

+ | *numpy_fft.example | ||

+ | |||

+ | |||

+ | |||

+ | == Image processing == | ||

+ | |||

+ | Look at [http://prancer.physics.louisville.edu/classes/650/python/examples our server] for examples using PIL and PyFITS. | ||

+ | |||

+ | To rotate and flip an image in PIL -- | ||

+ | |||

+ | *png_image_rotate.example | ||

+ | *png_image_flip.example | ||

+ | |||

+ | |||

+ | |||

+ | == User interfaces == | ||

+ | |||

+ | Look at [http://prancer.physics.louisville.edu/classes/650/python/examples our server] for these examples | ||

+ | |||

+ | *interpolate_plot.example Shows how to interact with the operating system through the command line. | ||

+ | |||

+ | *gui_buttons.example Shows how to add buttons to a window and set up callbacks. | ||

+ | |||

+ | *pyplot_data.example Shows how to incorporate a matplotlib figure in your own canvas with new buttons. |

This page contains examples and links to programs used for our Research Methods - Programming with Python short course.

Start a Python interactive session using the "python" command to get a >>> prompt.

There are many built-in features of Python that are described in the documentation, but to get started let's do something very easy.

Type

>>>x=1

and then simply

>>>x

and you'll see

1

Type

>>>x=1.01

and then after you type "x" you'll see

>>>x 1.01

Clearly you have a real-time calculator in hand, so try something more exciting.

>>>x=1.01 >>>y=1.0001 x/y

and you'll see something like this

1.0098990100989902

Modify that with

>>>z=x/y >>>z

and you'll see the same result. But now try

>>>int(z)

and you'll see

1

That is, the function int() took the integer part of z. You can put that in another variable such as

>>>a=int(z) >>>a 1

Curiously, a seems to be an integer. It is said to be *dymanically typed* in this assignment. That can change. If you now add a little bit to a you'll see it turns into a floating point number

>>>a = a + 0.001 >>>a 1.001

There's much more you can do, of course, but you need to import the math functions first. Here's one way to do that.

>>>import math

Now try

>>>math.pi

and you'll see

3.141592653589793

The functions in the math package need the "math." in front of them.

>>>math.sin(math.pi/4.)

returns

0.7071067811865475

as does

>>>math.sqrt(0.5)

Similarly

>>>4.*math.asin(math.sqrt(0.5))

returns

3.1415926535897936

The comprehensive list of math functions is on the Python documentation site. You can try out some of the more exotic possibilities on your own.

Let's turn off the real-time version of Python if you have it running by typing

exit()

or simply the combination of "ctrl" and "d"keys "ctrl+d" to return to the system prompt.

Select your favorite Python editor, and create a file we'll call test.py . If you have the Python interpreter associated with a .py extension, then when you click on a this file in a graphical user interface (regardless of the operating system) it will run "python test.py" and give you the result of the program in the file. Alternatively, in Linux or MacOS, if the first line of the file is

#!/usr/bin/python

this will tell the user interface to run python followed by the code that is in the file (assuming that the executable "python" program is in /usr/bin. Here is how you would write a "Hello World" program in python:

#!/usr/bin/python print "Hello World!\n" exit()

Hint here: the "\n" is a line feed that will create a blank line after printing the text.

Now to run this program in MacOS or Linux you would make sure it's executable

ls -l test.py

returns

-rwxr-xr-x 1 john users 48 Feb 7 02:16 test.py

which tells me that I own the program and that I can execute it (The letters in groups in the listing of the program give the permissions, and the "x" means execute, "r" means read, and "w" means write. The first three are for the user who owns the file, the second three are for the group that use belongs to, and the last three are for everybody else.) With that, I can simply type

./test.py

which means "run the program in this directory called test.py". The prefatory "./" is not needed if the PATH includes the current directory. Obviously there are operating system nuances here that have nothing in particular to do with Python, but have to be mastered to use the computer to its fullest. Alternatively on any system you can explictly ask for the python program

python test.py

which will take "test.py" as input and run it. In either case, you will see

Hello World!

This is a an example of a Python program that asks for a value, calculates a result, and displays it for the user. The source code is available here in the file *trig.example* . Down load by right clicking and saving the file locally with the extension *.py* rather than *.example*.

#!/usr/bin/python

import math

# Print something for the user

print 'I will find trigometric functions for an angle.\n'

# Ask for a value for the angle

angle = raw_input('What is the angle in degrees? >> ')

# Convert the angle from degrees to radians and to the math

a = float(angle) arad = math.radians(a) sine = math.sin(arad) cosine = math.cos(arad) tangent = math.tan(arad)

# Output the results

print '\n' print 'Radians: ', arad print 'Sine: ', sine print 'Cosine: ', cosine print 'Tangent: ', tangent print '\n'

# Exit nicely

exit()

Suppose that we have a catalog of data containing information about astronomical objects, and we want to find the data in the catalog that are specifically for one entry, given my name. A typical use would be on the command line when that's possible, or by reading the name from another file. For this purpose we'll take the catalog called *ngc2000.dat* which contains all NGC and IC objects, read it, and find the one item we want.

A program illustrating the ideas we have discussed so far is available here. Look for ngc_reader.example and download it with a right click. The data file ngc2000.dat is also there.

The reader will look for this catalog in the same directory it is executing, and will expect an NGC or IC number on the command line. If your operating system does not handle command line input, try it with the number assigned as text within the program body, and delete the code that reads the command line.

Programs illustrating how to do simple 2D plotting that we discussed here are available here. Look for

- damped_cos.example
- two_plots.example
- two_overplots.example.

We have also copied a selection of the 3D plotting examples from matplotlib's source code to our server:

- contour3d_demo3.example
- rotate_axes3d_demo.example
- subplot3d_demo.example
- surface3d_demo2.example
- surface3d_demo.example
- trisurf3d_demo.example

You will also find with additional information in matplotlib's 3D tutorial.

Building on the damped_cos.example for plotting, the program numpy_fft.example on our server will make an interactive plot of the Fourier transform using NumPy's FFT routines. It also illustrates how to create and use NumPy arrays, rather than explicitly calculating lists element by element.

Other examples illustrate SciPy fitting, interpolation, integration and statistics:

- curve_fit_plot.example
- integrate_function_plot.example
- integrate_numerical_plot.example
- interpolate_noisy_plot.example
- interpolate_plot.example
- norm_probability_plot.example
- numpy_fft.example

Look at our server for examples using PIL and PyFITS.

To rotate and flip an image in PIL --

- png_image_rotate.example
- png_image_flip.example

Look at our server for these examples

- interpolate_plot.example Shows how to interact with the operating system through the command line.

- gui_buttons.example Shows how to add buttons to a window and set up callbacks.

- pyplot_data.example Shows how to incorporate a matplotlib figure in your own canvas with new buttons.