180 likes | 311 Views
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:
E N D
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...
BEFORE GETTING STARTED • 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.
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 49.015705
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 ... 49.015705
Dynamic whitespace • In python whitespace is important, unlike e.g. Perl. Your left hand indentation matters. So this will work: forxinrange(len(array)): printx y=x**2.7 printy print y # will print the last #value of y This won’t: for x in range(len(array)): print x y=x**2.7 printy printy# 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. importnumpy • 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: importnumpyasnp • 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’: fromnumpyimportsqrt , 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: defmy_function(arg1, arg2): z=np.sqrt(arg1)*np.exp(arg2) returnz • 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: • Calculating colour-colour plots from incomplete data lists. • Find the peak flux in a spectrum. • Finding Zeeman split line pairs and calculating the local magnetic field strength in ex-OH masers. • Calculating the rms noise in an ALMA map... Etcetc • 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... • APLpyfor making nice FITS images.
Examples resFOV.py
Basic syntax stuff and quick plot Page 1 of 2 importnumpyasnp importmatplotlib.pyplotasplt x=np.arange(1.0,10.0,1.0) #creates an array from 1 to 9 forvalueinx: ifvalue ==4.0: print“wow a 4!” elifvalue== 5.0: print “and now a 5!” else: printvalue y=np.sqrt(np.exp(x))#just for something to plot against x!
Basic syntax stuff and quick plot Page 2 of 2 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
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.