« Trying out the new camera | Main | A winter trip into the mountains »

Fitting data with python

As an astronomer I do lots of data fitting with python (utilising scipy) and thought it was about time I'd put up one of my basic procedures:

#!/usr/bin/python #by Samuel George; 03/02/2011
import matplotlib; matplotlib.use('Agg') #avoid X11 issues.
import scipy, pylab, asciidata
from pylab import *
from scipy import optimize
from scipy.stats.stats import spearmanr as spearcor

def fitting_func(logx, logy, logyerr): # fitting
     fitfun = lambda p, x: p[0] + p[1] * x # define fitting function
     errfun = lambda p, x, y, yerr: (y - fitfun(p, x)) / yerr
     p0 = [0.0, 0.0]
     out = optimize.leastsq(errfun, p0, args=(logx, logy, logyerr), full_output=1)
     index = out[0][1]
     amp = 10.0**out[0][0]
     index_Err = sqrt( out[1][0][0] )
     amp_Err = sqrt( out[1][1][1] ) * amp
     r = spearcor(logx,logy) #Spearman rank correlation test
     return out[0],out[1],index,amp,index_Err,amp_Err,r #p[0], p[1], covariance matrix, index of powerlaw, amp powerlaw, errors+spearman rank

pout, covar,index,amp,indexErr,ampErr,r = fitting_func(log10(xdata), log10(ydata), (errory / log10(ydata)))

This code can also be found [here]

TrackBack

TrackBack URL for this entry:
http://krioma.net/cgi-bin/MT-3.38/mt-tb.cgi/481

Listed below are links to weblogs that reference Fitting data with python:

» Gaussian Fitting in python from Krioma.net Blog
I spend a lot of my time working on noise statistics and of course and an important part of this is how to fit signals. I was asked earlier for an example code on how to fit a Gaussian, in... [Read More]

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on February 4, 2011 2:00 AM.

The previous post in this blog was Trying out the new camera.

The next post in this blog is A winter trip into the mountains.

Many more can be found on the main index page or by looking through the archives.

Get Firefox! Valid XHTML 1.0! Valid CSS! RSS Feed BlogUniverse - listed Powered by Apache Creative Commons License ringsofsaturnrock's Most Interesting Photos on Flickriver

Powered by
Movable Type 3.38