Guest User

Untitled

a guest
Oct 27th, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from scipy import optimize
  4. import itertools
  5. import sys
  6. import math
  7.  
  8. def readData(filename):
  9.     f = open(filename, 'r')
  10.     titles = f.readline().rstrip('\n\r').split(',')
  11.     dots = []
  12.     lines = f.readlines()
  13.     f.close()
  14.     for line in lines:
  15.         dots.append([float(s) for s in line.rstrip('\\').split(',')])
  16.     #transposing dots for convinience
  17.     dots = map(list, zip(*dots))
  18.     return (titles, dots)
  19.  
  20. def fit(f, x, y, *args):
  21.     popt = optimize.curve_fit(f, x, y, args)
  22.     newx = np.linspace(x [0], x [-1], 100)
  23.     newy = f(newx, *(popt [0]))
  24.     return (newx, newy)
  25.  
  26. def fitPlot(title, columns, dots, f, *args):
  27.     #building x and xerror
  28.     x = np.array(dots [0])
  29.     firstValue = 1
  30.     xerror = np.array([0.0] * len(x))
  31.     if '\delta' in columns [1]:
  32.         firstValue += 1
  33.         xerror = np.array(dots [1])
  34.     #each plot has individual marker
  35.     marker = itertools.cycle(('x', 'o', 'D', '*', 'v', '^', '+', 'h'))
  36.     #plotting
  37.     for i in xrange(firstValue, len(dots)):
  38.         if '\delta' in columns [i]:
  39.             plt.errorbar(x, dots [i - 1], yerr = dots [i], fmt = None, ecolor = 'black')
  40.         else:
  41.             plt.plot(x, dots [i], marker = marker.next(), linestyle = '', color = 'black', label = columns [i])
  42.             #fitting
  43.             fitx, fity = fit(f, x, np.array(dots [i]), *args)
  44.             plt.plot(fitx, fity, color = 'black')
  45.             plt.errorbar(x, dots [i], xerr = xerror, fmt = None, ecolor = 'black')
  46.     #some eye-candy
  47.     plt.title(title)
  48.     plt.xlabel(columns [0])
  49.     plt.legend(loc = 'best', fancybox = True, numpoints = 1)
  50.     plt.grid(True)
  51.  
  52. if __name__ == "__main__":
  53.     columns, dots = readData('plot_data.csv')
  54.     #example of polynomial fitting
  55.     #f = lambda x, a, b, c: (a * x + b) * x + c
  56.     #example of elementary function fitting
  57.     f = lambda x, a, b, c: [a * math.exp(arg * arg * b) + c for arg in x]
  58.     a, b, c = 1.0, -0.25, 1.0
  59.     fitPlot('$simple\,plot$', columns, dots, f, a, b, c)
  60.     plt.ylabel('$F\,and\,U\,values$')
  61.     plt.show()
Advertisement
Add Comment
Please, Sign In to add comment