Python: Your new best friend print “Adam Avison”
Disclaimer Though I’ve extensively programmed in Python, I have ~0 formal programming training. So some terminology I use may be total gibberish to those better taught than I. My mantra is: “If it works it works, who cares about the fancy terminology”.
Python version Here I will talk about functions within Python 2.6.x / 2.7.x (the JBCA system default) The separate development stream of Python 3.x... Most of what I say won’t work, or will work very differently.
Why Python? The current astronomers favourite... CASA (interferometric data reduction package is written in it). Its free! (unlike IDL...*) *I’m yet to find something IDL can do that Python can’t...
Why Python?
First we need to set up which version of python your linux box will default to. In your home area type: >emacs –nw.cshrc This will open an in terminal text editor. Press the down key until you see the line: #USER MODIFICATIONS After this type alias python2.7 ‘/usr/local/lib/python2.7/bin/python2.7’ The type ctrl-x ctrl-s. Close your terminal and open another and we’re good to go. BEFORE GETTING STARTED
Getting started From the command line ‘python’ will get you into the python environment. Within which you can start some basic work. e.g. >>> a=3.141*0.005 >>> b=7.0**2.0 >>> c=a+b >>> print c
Scripting Adding those lines into a file named e.g. ‘test.py’ will then be executable by the command >python test.py Will result in
Dynamic whitespace In python whitespace is important, unlike e.g. Perl. Your left hand indentation matters. So this will work: for x in range(len(array)): print x y=x**2.7 print y print y # will print the last #value of y This won’t: for x in range(len(array)): print x y=x**2.7 print y print y # we’ll have crashed #before we reach here Remember for later your ‘if’s, ‘elif’s and ‘else’s need to line up!
Importing modules A lot of functionality can be imported into your scripts with import commands e.g. import numpy As python is object orientated you call a ‘numpy’ task as follows: numpy.sqrt(2.0) #will give us square-root of 2 But because we’re lazy we don’t want to type numpy over and over so we can instead use: import numpy as np So the above becomes np.sqrt(2.0) #will still give us square-root of 2
Importing modules 2. Some times we only want a couple of functions from a module for this we can use a ‘from’: from numpy import sqrt, other_function Now: sqrt(2.0) #will give us what we’re after
Why isn’t there a function for this? If the function you’re after doesn’t exist... Write your own! In your code you can create your own functions, here is an example: def my_function(arg1, arg2): z=np.sqrt(arg1)*np.exp(arg2) return z Which can then be called later in your code simply as: something=my_function(arg1, arg2)#something will then == z With the same number of arguments.
Example functions Example functions I’ve created: 1.Calculating colour-colour plots from incomplete data lists. 2.Find the peak flux in a spectrum. 3.Finding Zeeman split line pairs and calculating the local magnetic field strength in ex-OH masers. 4.Calculating the rms noise in an ALMA map... Etc etc Functions are good because they mean you don’t have to re- type code umpteen times throughout a script.
Useful python modules for Astronomy numpy – array and matrix mathematics, nice load from txt options... scipy – Scientific functions, e.g. correlation, signal processing, ffts... matplotlib – plotting... Makes beautiful plots. pyfits – FITS file manipulation. astropy - many useful astronomy modules and packages all in one... APLpy for making nice FITS images.
Examples resFOV.py
Basic syntax stuff and quick plot Page 1 of 2 import numpy as np import matplotlib.pyplot as plt x=np.arange(1.0,10.0,1.0) #creates an array from 1 to 9 for value in x: if value ==4.0: print “wow a 4!” elif value == 5.0: print “and now a 5!” else: print value y=np.sqrt(np.exp(x)) #just for something to plot against x!
fig1 = plt.figure(1) ax1 = fig1.add_subplot(111) #sets up a plot environment to # plot on ax1.plot(x,y,’bo-’) #plots x v. y, ‘bo-’ sets it to #plot blue circles with a solid #line joining them ax1.set_xlabel(‘x’) ax1.set_ylabel(‘y’)#take a guess! plt.show()#shows our plot Basic syntax stuff and quick plot Page 2 of 2
Challenge Using the basics demonstrated in this tutorial write a script which calculates the Schwarzschild radius for black holes of mass = to each of the solar system planets. Extra credit, plot mass vs. radii and label each planet.