Until recently I had never been a fan of IPython but with their HTML notebook they’ve finally won me over. What I like about this tool is that it makes it easy to go back and forth between interactive prototyping and a script. Being able to continuously edit and re-run code in an interactive session is a powerful tool.
A colleague recently asked for help getting the functionality of IDL’s GAUSSFIT function working in Python. This was a perfect opportunity to use the handy curve_fit function from SciPy. Here’s the code:
import numpy as np
from scipy.optimize import curve_fit
xdata, ydata = np.loadtxt('focus_output.dat', unpack=True)
def fit_func(x, a0, a1, a2, a3, a4, a5):
z = (x - a1) / a2
y = a0 * np.exp(-z**2 / a2) + a3 + a4 * x + a5 * x**2
parameters, covariance = curve_fit(fit_func, xdata, ydata)
The file focus_output.dat just contains some data in two columns of numbers. For more info on loadtxt see my post on reading text tables. fit_func defines the function we want to fit to the data. In this case it is a Gaussian plus a quadratic, the same as used in GAUSSFIT when NTERMS=6. Now, to plot the results:
Reading tables is a pretty common thing to do and there are a number of ways to read tables besides writing a read function yourself. That’s not to say these are magic bullets. Every table is different and can have its own eccentricities. If you find yourself reading the same type of quirky file over and over again it could be worth your effort to write your own reader that does things just the way you like. That said, here are some other options.
I personally use the CIY method because it allows me to very easily control what’s installed. With Homebrew and pip I can uninstall and upgrade different things at will, or choose to install bleeding-edge versions. But it’s more hassle than everyone wants and there’s now an easier way using double-click installers.
Until recently the CIY was the only way to get everything working on Lion but now the developers of NumPy, SciPy, and matplotlib have all caught up and it’s possible to just download and double-click on a few DMG files to get a basic scientific Python installation working. Once you get to know Python, though, you will undoubtedly want to install some other packages and when that time comes I suggest you use pip.