Posted By


dancohen990 on 09/10/13

Tagged


Statistics


Viewed 553 times
Favorited by 0 user(s)

interferogram.py


/ Published in: Python
Save to your folder(s)

A program I wrote for data analysis during my final project at university.


Copy this code and paste it in your HTML
  1. '''A program to analyse and plot the data from an interferometer experiment with TK power meter.'''
  2. import os.path
  3. import matplotlib.pyplot as plt
  4. import string
  5. import glob
  6. import matplotlib
  7.  
  8. font = {'family' : 'normal',
  9. 'weight' : 'bold',
  10. 'size' : 22}
  11.  
  12. matplotlib.rc('font', **font)
  13.  
  14. def generateListIncre(Min, Max, Increment):
  15. '''a function to generate and return a list of float values from 3 float inputs.
  16. Increments between Min and Max by Increment.'''
  17. newList = []
  18. i = Min
  19. while i!=Max:
  20. newList.append(i)
  21. i = i + Increment
  22. if i > Max:
  23. print 'Error in incrementing function in generateListIncre - Line 45'
  24. return(newList)
  25. newList.append(i)
  26. return(newList)
  27.  
  28.  
  29. def tryFloat(rawInputString):
  30. '''is an exception handler - tries to convert to float - if fails repeats input request
  31. takes a raw_input() as an argument and returns a float'''
  32. try:
  33. floatArg = float(raw_input(rawInputString))
  34. except ValueError:
  35. print '\nYour input produced a ValueError. \n Please ensure your input is an integer or decimal - no alphabet characters.\n'
  36. floatArg = tryFloat(rawInputString)
  37. return(floatArg)
  38.  
  39.  
  40. def getList(axis):
  41. '''a function to get the xList from user input. The axis argument is used
  42. to construct the user interface and represents the x, y or z axis'''
  43. optionError = True
  44. listArg = []
  45. while optionError == True:
  46. incrOpt = raw_input('\nTo enter OPL (optical path length) as MAX,MIN and INCREMENT, enter 1. Else,'
  47. + ' to enter as a list enter 2: ')
  48. if incrOpt == '1':
  49. optionError = False
  50. minMaxValid = False
  51. while minMaxValid == False:
  52. MIN = tryFloat('Please enter the OPL minimum: ')
  53. MAX = tryFloat('Please enter the OPL maximum: ')
  54. if MIN == MAX or MIN > MAX:
  55. print 'Your values for MIN and MAX are invalid.'
  56. else:
  57. minMaxValid = True
  58. INCRValid = False
  59. while INCRValid == False:
  60. INCR = tryFloat('Please enter the increment: ')
  61. if INCR > (MAX-MIN):
  62. print 'Your increment is too large.'
  63. elif INCR == 0:
  64. print 'Cannot have a Zero increment.'
  65. else:
  66. INCRValid = True
  67. listArg = generateListIncre(MIN, MAX, INCR)
  68. elif incrOpt == '2':
  69. optionError = False
  70. finished = False
  71. print('Please input the list of OPL positions 1 at a time. To end the list, input end')
  72. i = 0
  73. while finished == False:
  74. i += 1
  75. tempInput = raw_input('Input OPL' + str(i) + ': ')
  76. if tempInput.lower() == 'end':
  77. finished = True
  78. else:
  79. try:
  80. listArg.append(float(tempInput))
  81. except ValueError:
  82. print 'Please ensure the input is either integer or decimal. No alphabet characters.'
  83. i -= 1
  84. else:
  85. print 'Your input produced an error, please enter either 1 or 2'
  86. optionError = True
  87. return(listArg)
  88.  
  89. def processDataNoInput(freq,rootFolderName):
  90. '''a function to process all the data with no need for user input more than root dir'''
  91. outFileName = rootFolderName+str(freq)+'GHz_mean_sdev.txt'
  92. outFile = open(outFileName, 'w')
  93. outFile.write('Interferometer Measurements\n Nominal Frequency = ' + str(freq) + 'GHz\n')
  94. outFile.write('x(mm)\tMean (W)\tError (W)\n')
  95. dirList = glob.glob(rootFolderName+str(freq)+'GHz/*')
  96. for i in range(len(dirList)):
  97. if os.path.isdir(dirList[i]):
  98. dirList.pop(i);
  99. sortDirList(dirList)
  100. for i in dirList:
  101. print 'i = ', i
  102. inputFile = open(i, 'r')
  103. dataList = []
  104. dataList = inputFile.readlines()
  105. dataList.pop(0)
  106. dataList.pop(0)
  107. dataList.pop(0)
  108. dataList.pop(0)
  109. for k in range(len(dataList)):
  110. dataList[k] = string.split(dataList[k])
  111. dataMean = mean(dataList)
  112. dataSDev = sDev(dataList)
  113. outFile.write(str(i[findStartNum(i):]))
  114. outFile.write('\t'+str(dataMean) + '\t'+ str(dataSDev)+'\n')
  115. print '>>> data successfully written to ', outFileName
  116. return(outFileName)
  117.  
  118. def mean(listOfData):
  119. '''takes a list(input) of data from TK Power Meter and finds the mean of all the voltages(returns float)'''
  120. sum = 0.00
  121. total = 0.00
  122. for i in range(len(listOfData)):
  123. tempList = listOfData[i]
  124. sum += float(tempList[1])
  125. total += 1.00
  126. mean = sum/total
  127. return mean
  128.  
  129. def sDev(listOfData):
  130. '''takes a list(input) of data from TK Power Meter and finds the standard deviation
  131. of all the voltages(returns float)'''
  132. sDevMean = mean(listOfData)
  133. N = len(listOfData)
  134. sum = 0.00
  135. for i in range(N):
  136. tempList = listOfData[i]
  137. operand = float(tempList[1]) - sDevMean
  138. sum+= operand**2
  139. standardDeviation = operand/float(N)
  140. return standardDeviation
  141.  
  142. def getXDistwErrors(dataList):
  143. '''generates a list of x values, a list of data points and a list of errors where the xvalues are dataList[i][0], data points are dataList[i][1] and errors are dataList[i][2]. Returns a nested list where nestedList = [xValues, dataPoints, errors]'''
  144. xValues = []
  145. dataPoints = []
  146. errors = []
  147. for i in dataList:
  148. xValues.append(float(i[0]))
  149. dataPoints.append(float(i[1]))
  150. errors.append(float(i[2]))
  151. return([xValues, dataPoints, errors])
  152.  
  153. def findStartNum(stringArg):
  154. '''given string with number at the end, returns the index where the number at the end begins.'''
  155. i = len(stringArg)-1
  156. while i > 0:
  157. if stringArg[i] in string.digits or stringArg[i] == '-' or stringArg[i] == '.' or stringArg[i] in string.whitespace:
  158. i-=1
  159. elif stringArg[i] == '=' or stringArg[i] == 'x' or stringArg[i] in string.ascii_letters or stringArg[i] in string.punctuation:
  160. return i+1
  161. else:
  162. i-=1
  163. return i
  164.  
  165. def sortDirList(dirList):
  166. '''sorts a listArg by list[i][0][30:]'''
  167. newList = []
  168. numStart = findStartNum(dirList[0])
  169. tempStr = dirList[0][:numStart]
  170. for i in dirList:
  171. newList.append([i[numStart:]])
  172. finished = False
  173. level = 0
  174. i = 0
  175. j = 0
  176. k = 0
  177. tempList = []
  178. checkLen = len(newList)
  179. while len(newList)!=1:
  180. while i < checkLen-1:
  181. finished = False
  182. while finished == False:
  183. if len(newList[i]) == j and len(newList[i+1]) == k:
  184. newList[i] = tempList[:]
  185. tempList = []
  186. newList.pop(i+1)
  187. i+=1
  188. j = 0
  189. k = 0
  190. checkLen = len(newList)
  191. finished = True
  192. elif len(newList[i]) == j:
  193. tempList.append(newList[i+1][k])
  194. k+=1
  195. elif len(newList[i+1])==k:
  196. tempList.append(newList[i][j])
  197. j+=1
  198. elif float(newList[i][j]) < float(newList[i+1][k]):
  199. tempList.append(newList[i][j])
  200. j+=1
  201. else:
  202. tempList.append(newList[i+1][k])
  203. k+=1
  204. if len(newList[-1]) == 1:
  205. j = 0
  206. k = 0
  207. done = False
  208. while done == False:
  209. if len(newList[-1]) == k and len(newList[-2]) == j:
  210. done = True
  211. j = 0
  212. k = 0
  213. newList[-2] = tempList[:]
  214. newList.pop(-1)
  215. tempList = []
  216. elif len(newList[-1]) == k:
  217. tempList.append(newList[-2][j])
  218. j +=1
  219. elif len(newList[-2]) == j:
  220. tempList.append(newList[-1][k])
  221. k += 1
  222. elif float(newList[-1][k])<float(newList[-2][j]):
  223. tempList.append(newList[-1][k])
  224. k+=1
  225. else:
  226. tempList.append(newList[-2][j])
  227. j+=1
  228. i = 0
  229. for i in range(len(newList[0])):
  230. tempStr2 = tempStr + str(newList[0][i])
  231. dirList[i] = tempStr2
  232.  
  233. finished=False
  234. dirSame = False
  235. print('\nThis program analyses the interferogram data from the TK power meter and then plots a graph of x-position versus intensity.\n')
  236. while finished == False:
  237. dirFound = False
  238. if dirSame == False:
  239. rootFolderName = ''
  240. while dirFound == False:
  241. rootFolderName = raw_input('Please enter the data root folder: ')
  242. if rootFolderName[-1] != '/':
  243. rootFolderName+='/'
  244. dirFound = os.path.exists(rootFolderName)
  245. if dirFound == False:
  246. print 'Directory not found.'
  247. freq = raw_input('Please input the frequency the emitter is set to: ' )
  248. iFi = open(processDataNoInput(freq, rootFolderName))
  249. lines = iFi.readlines()
  250. lines.pop(0)
  251. freqString = lines.pop(0)
  252. unitsString = lines.pop(0)
  253. plotList=[]
  254. for i in range(len(lines)):
  255. plotList.append(string.split(lines[i]))
  256. plotList = getXDistwErrors(plotList)
  257. for i in range(len(plotList[1])):
  258. plotList[1][i]=plotList[1][i]*1000
  259. plt.figure()
  260. plt.errorbar(plotList[0],plotList[1],yerr=plotList[2])
  261. plt.xlabel('Position (mm)')
  262. plt.ylabel('Power ('+'mW)')
  263. plotTitle = str(freq) + 'GHz Interferogram'
  264. plt.title(plotTitle)
  265. fin = raw_input('If you need to analyse more data in the same rootdir, enter "1"\nif you need a new root dir, enter "2" \nelse enter anything: ')
  266. if fin != '1' and fin != '2':
  267. finished = True
  268. elif fin == '1':
  269. dirSame = True
  270. else:
  271. dirSame = False
  272.  
  273.  
  274. plt.show()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.