Advertisement
Guest User

Untitled

a guest
May 5th, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.32 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sun Nov 03 20:32:01 2013
  4.  
  5. INSTRUCTIONS
  6. ~~~~~~~~~~~~
  7.  
  8. This is a template file for you to use for your Computing 2 Coursework.
  9.  
  10. Save this file as py12spqr.py when py12spqr should be replaced with your ISS username
  11.  
  12. Do not rename or remove the function ProcessData, the marking will assume that this function exists
  13. and will take in the name of a data file to open and process. It will assume that the function will return
  14. all the answers your code finds. The results are returned as a dictionary.
  15.  
  16. Your code should also produce the same plot as you produce in your report.
  17.  
  18. @author: phygbu
  19. """
  20.  
  21. def ProcessData(filename):
  22.  
  23. try:
  24. Metadata = GetData(filename)[0]
  25. xdata = GetData(filename)[1]
  26. ydata = GetData(filename)[2]
  27. FullPlot(xdata, ydata, "Magnetic Field (A/m)", "Absorption (arb units)", "py13kb Results for 20GHz", "ro", "m")
  28. Peakat = ((Lorfit(xdata, ydata))[0])[0]
  29. Peakwid = ((Lorfit(xdata, ydata))[0])[1]
  30.  
  31. except ValueError or NameError or Exception:
  32. print "Something went horribly wrong"
  33. sys.exit()
  34.  
  35. results={"20GHz_peak":None, #this would be the peak position at 20GHz
  36. "20GHz_width": None, #Delta H for 20 GHz
  37. "gamma": None, #your gamma value
  38. "g": None, #Your Lande g factor
  39. "Hk": None, #Your value for the anisotropy field
  40. "Ms": None, #Your value for trhe sauration Magnetisation
  41. "DeltaH": None, #Your value ffor the intrinsic line width
  42. "alpha": None }# Your value for the Gilbert Damping parameter
  43.  
  44. results["20GHz_peak"] = Peakat
  45. results["20GHz_width"] = Peakwid
  46.  
  47. #If your code doesn't find all of these values, just leave them set to None
  48. #Otherwise return the number. Your report should also give the errors in these numbers.
  49.  
  50. return results
  51.  
  52. if __name__=="__main__":
  53. import math
  54. from math import sqrt
  55. import numpy as np
  56. from numpy import diag
  57. from itertools import ifilter as Filt
  58. import matplotlib.pyplot as plt
  59. from scipy.optimize import curve_fit
  60. import sys
  61.  
  62. def GetData(Filename):
  63. #Will make sure that the file names are correct, and display a message if they are not
  64. try:
  65. with open(Filename, "r") as Datafile:
  66.  
  67. Metadataprep = Filt(lambda x: x[0:3].isdigit() == False and x[0:3] != "0.0", Datafile) #filters out all the lines that are exclusively numeric data
  68. Metadata = np.genfromtxt(Metadataprep, delimiter="\t", #reads the non-numeric data into an array
  69. autostrip=True, #I have done it this way in case the metadata messes up and doesn't put in the "&END" or somesuch, even though it is more cumbersome
  70. skip_footer=1,
  71. dtype = str
  72. )
  73. while Metadata[0] == "&SRS" or Metadata[0] == "<MetaDataAtStart>":
  74. Metadata = np.delete(Metadata, [0]) #Trimms off the metadata and SRS for neatness' sake, though there must be a better way to do this
  75.  
  76. Metadata = Metadata[::-1]
  77.  
  78. while Metadata[0] == "&END" or Metadata[0] == "</MetaDataAtStart>":
  79. Metadata = np.delete(Metadata, [0])
  80.  
  81. Metadata = Metadata[::-1] # Finally finished trimming
  82.  
  83. with open(Filename, "r") as Datafile:
  84.  
  85. Dataprep = Filt(lambda x: x[0:3].isdigit() or x[0:3] == "0.0", Datafile) #filters out all the lines that are not exclusively numeric data within reason
  86. Data = np.genfromtxt(Dataprep, delimiter="\t", #reads the numeric data into an array
  87. autostrip=True,
  88. )
  89. xdata = Data[:,0] #Assigning the data to the final names to be returned
  90. ydata = Data[:,1] #Worth noting that by putting a ":" after the 1 here, the Plotme function will work for multiple frequencies, but fitting is not coded to accomodate this
  91.  
  92.  
  93.  
  94. return Metadata, xdata, ydata
  95. except Exception or NameError:
  96. print "An error has occured retrieving the file"
  97.  
  98. def Plotme(Xdata, Ydata, XAxisLabel, YAxisLabel, Title): #Basic plotting function, input your data and it'll plot for you
  99. plt.plot(Xdata, Ydata)
  100. plt.title(Title)
  101. plt.ylabel(YAxisLabel)
  102. plt.xlabel(XAxisLabel)
  103. plt.show()
  104.  
  105.  
  106. def FPlotme(Xdata, Ydata, Yfit, XAxisLabel, YAxisLabel, Title, Col1, Col2): #Specific plotting function designed to be called by FullPlot, but usable itself
  107. plt.plot(Xdata, Ydata, Col1,\
  108. Xdata, Yfit, Col2)
  109. plt.title(Title)
  110. plt.ylabel(YAxisLabel)
  111. plt.xlabel(XAxisLabel)
  112.  
  113. def lorentz(xdata, peak, peakwid, K): #Lorentx function for fitting purposes
  114. y = (float(K)*0.5*math.pi) * (float(peakwid) / ((xdata - float(peak))**2 + (float(peakwid)/2)**2)) #The floats are important or it evaluates to zero midway
  115. return y
  116.  
  117. def Lorfit(x, y): #fits x and y using the lorentzian function, returns an array of Values for the Peak, Peakwidth and K factor, and then an array for the covariance matrix
  118. LorValues, LorErr=curve_fit(lorentz, x, y, p0=[300000, 20000, 80000]) #the guesses are based on the 20GHz data, but don't matter much
  119. return LorValues, LorErr
  120.  
  121. def Annotate(): #Annotation function that when working with Lorfit will produce annotations for a plot, giving you the Peak, Peak Width, and K factor
  122. Peakanno1 = "Peak at " + str((Lorfit(xdata, ydata)[0])[0]) + " +- " + str(GetError(xdata, ydata, 0))
  123. Peakanno2 = "Peak width is " + str((Lorfit(xdata, ydata)[0])[1]) + " +- " + str(GetError(xdata, ydata, 1))
  124. Peakanno3 = "K factor is " + str((Lorfit(xdata, ydata)[0])[2]) + " +- " + str(GetError(xdata, ydata, 2))
  125. Peak = (Lorfit(xdata, ydata)[0])[0]
  126.  
  127.  
  128. plt.annotate(Peakanno1, xy=(Peak, ydata.max()),
  129. xytext = (30, -20), textcoords = 'offset points',
  130. arrowprops = dict(arrowstyle="->"))
  131.  
  132. plt.annotate(Peakanno2, xy=(Peak, ydata.max()),
  133. xytext = (30, -40), textcoords = 'offset points')
  134.  
  135. plt.annotate(Peakanno3, xy=(Peak, ydata.max()),
  136. xytext = (30, -60), textcoords = 'offset points')
  137.  
  138.  
  139. def FullPlot(X, Y, Xax, Yax, Title, Col1, Col2): #A Function that will return a full plot including the fitting analysis and annotations
  140. Lorfit(X, Y)
  141. Yfit = lorentz(X, (Lorfit(X, Y)[0])[0], (Lorfit(X, Y)[0])[1], (Lorfit(X, Y)[0])[2])
  142. FPlotme(X, Y, Yfit, Xax, Yax, Title, Col1, Col2)
  143. Annotate()
  144. plt.show()
  145.  
  146. def GetError(xdata, ydata, n): #Uses LorFit to grab the covariance matrix and reads out the nth Lorfit value's error
  147. Error = sqrt(((Lorfit(xdata, ydata))[1])[n,n])
  148. return Error
  149. filename="My Data File.txt"
  150. test_results=ProcessData(filename)
  151. print test_results
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement