Surface NMR processing and inversion GUI
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

mrsurvey.py 113KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  1. from PyQt5.QtCore import *
  2. import numpy as np
  3. import scipy.signal as signal
  4. import pylab
  5. import sys
  6. import scipy
  7. import copy
  8. import struct
  9. from scipy.io.matlab import mio
  10. from numpy import pi
  11. from math import floor
  12. import matplotlib as mpl
  13. from matplotlib.ticker import FuncFormatter
  14. import matplotlib.font_manager as fm
  15. import matplotlib.pyplot as plt
  16. import matplotlib.ticker
  17. from matplotlib.ticker import MaxNLocator
  18. import multiprocessing
  19. import itertools
  20. import akvo.tressel.adapt as adapt
  21. #import akvo.tressel.cadapt as adapt # cython for more faster
  22. import akvo.tressel.decay as decay
  23. import akvo.tressel.pca as pca
  24. import akvo.tressel.rotate as rotate
  25. import akvo.tressel.cmaps as cmaps
  26. import cmocean # colormaps for geophysical data
  27. plt.register_cmap(name='viridis', cmap=cmaps.viridis)
  28. plt.register_cmap(name='inferno', cmap=cmaps.inferno)
  29. plt.register_cmap(name='inferno_r', cmap=cmaps.inferno_r)
  30. plt.register_cmap(name='magma', cmap=cmaps.magma)
  31. plt.register_cmap(name='magma_r', cmap=cmaps.magma_r)
  32. def loadGMRBinaryFID( rawfname, istack, info ):
  33. """ Reads a single binary GMR file and fills into DATADICT
  34. """
  35. #################################################################################
  36. # figure out key data indices
  37. # Pulse
  38. nps = (int)((info["prePulseDelay"])*info["samp"])
  39. npul = (int)(self.pulseLength[0]*self.samp) #+ 100
  40. # Data
  41. nds = nps+npul+(int)((self.deadTime)*self.samp); # indice pulse 1 data starts
  42. nd1 = (int)(1.*self.samp) # samples in first pulse
  43. invGain = 1./self.RxGain
  44. invCGain = self.CurrentGain
  45. pulse = "Pulse 1"
  46. chan = self.DATADICT[pulse]["chan"]
  47. rchan = self.DATADICT[pulse]["rchan"]
  48. rawFile = open( rawfname, 'rb')
  49. T = N_samp * self.dt
  50. TIMES = np.arange(0, T, self.dt) - .0002 # small offset in GMR DAQ?
  51. for ipm in range(self.nPulseMoments):
  52. buf1 = rawFile.read(4)
  53. buf2 = rawFile.read(4)
  54. N_chan = struct.unpack('>i', buf1 )[0]
  55. N_samp = struct.unpack('>i', buf2 )[0]
  56. DATA = np.zeros([N_samp, N_chan+1])
  57. for ichan in range(N_chan):
  58. DATADUMP = rawFile.read(4*N_samp)
  59. for irec in range(N_samp):
  60. DATA[irec,ichan] = struct.unpack('>f', DATADUMP[irec*4:irec*4+4])[0]
  61. return DATA, TIMES
  62. class SNMRDataProcessor(QObject):
  63. """ Revised class for preprocessing sNMR Data.
  64. Derived types can read GMR files
  65. """
  66. def __init__(self):
  67. QObject.__init__(self)
  68. self.numberOfMoments = 0
  69. self.numberOfPulsesPerMoment = 0
  70. self.pulseType = "NONE"
  71. self.transFreq = 0
  72. self.pulseLength = np.zeros(1)
  73. self.nPulseMoments = 0
  74. self.dt = 0
  75. def mfreqz(self, b,a=1):
  76. """ Plots the frequency response of a filter specified with a and b weights
  77. """
  78. import scipy.signal as signal
  79. pylab.figure(124)
  80. w,h = signal.freqz(b,a)
  81. w /= max(w)
  82. w *= .5/self.dt
  83. h_dB = 20 * pylab.log10 (abs(h))
  84. pylab.subplot(211)
  85. #pylab.plot(w/max(w),h_dB)
  86. pylab.plot(w,h_dB)
  87. pylab.ylim(-150, 5)
  88. pylab.ylabel('Magnitude (dB)')
  89. #pylab.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
  90. pylab.xlabel(r'Hz')
  91. pylab.title(r'Frequency response')
  92. pylab.subplot(212)
  93. h_Phase = pylab.unwrap(pylab.arctan2(pylab.imag(h), pylab.real(h)))
  94. #pylab.plot(w/max(w),h_Phase)
  95. pylab.plot(w,h_Phase)
  96. pylab.ylabel('Phase (radians)')
  97. pylab.xlabel(r'Hz')
  98. #pylab.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
  99. pylab.title(r'Phase response')
  100. pylab.subplots_adjust(hspace=0.5)
  101. def mfreqz2(self, b, a, canvas):
  102. "for analysing filt-filt"
  103. import scipy.signal as signal
  104. canvas.reAx2(False,False)
  105. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  106. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  107. #canvas.ax2.tick_params(axis='both', which='minor', labelsize=6)
  108. #pylab.figure(124)
  109. w,h = signal.freqz(b,a)
  110. w /= max(w)
  111. w *= .5/self.dt
  112. h_dB = 20 * pylab.log10(abs(h*h) + 1e-16)
  113. #ab.subplot(211)
  114. #pylab.plot(w/max(w),h_dB)
  115. canvas.ax1.plot(w,h_dB)
  116. canvas.ax1.set_ylim(-150, 5)
  117. canvas.ax1.set_ylabel('Magnitude [db]', fontsize=8)
  118. #pylab.xlabel(r'Normalized Frequency (x$\pi$rad/sample)')
  119. canvas.ax1.set_xlabel(r'[Hz]', fontsize=8)
  120. canvas.ax1.set_title(r'Frequency response', fontsize=8)
  121. canvas.ax1.grid(True)
  122. tt = np.arange(0, .02, self.dt)
  123. impulse = signal.dimpulse((self.filt_z, self.filt_p, self.filt_k, self.dt), t=tt)
  124. #impulse = signal.dstep((self.filt_z, self.filt_p, self.filt_k, self.dt), t=tt)
  125. #print impulse
  126. #for ii in range(len(impulse[1])):
  127. impulse_dB = 20.*np.log10(np.abs(np.array(impulse[1][0])))
  128. #canvas.ax2.plot(np.array(impulse[0]), impulse_dB)
  129. canvas.ax2.plot(np.array(impulse[0]), impulse[1][0])
  130. #h_Phase = pylab.unwrap(pylab.arctan2(pylab.imag(h), pylab.real(h)))
  131. #canvas.ax2.plot(w,h_Phase)
  132. canvas.ax2.set_ylabel('response [%]', fontsize=8)
  133. canvas.ax2.set_xlabel(r'time [s]', fontsize=8)
  134. canvas.ax2.set_title(r'impulse response', fontsize=8)
  135. #canvas.ax2.grid(True)
  136. canvas.draw()
  137. # search for last
  138. return impulse #[np.where(impulse[1][0] > .01)[-1]]
  139. class GMRDataProcessor(SNMRDataProcessor):
  140. # slots
  141. progressTrigger = pyqtSignal("int")
  142. doneTrigger = pyqtSignal()
  143. enableDSPTrigger = pyqtSignal()
  144. updateProcTrigger = pyqtSignal()
  145. def __init__(self):
  146. SNMRDataProcessor.__init__(self)
  147. self.maxBusV = 0.
  148. self.samp = 50000. # sampling frequency
  149. self.dt = 2e-5 # sampling rate
  150. self.deadTime = .0055 # instrument dead time before measurement
  151. self.prePulseDelay = 0.05 # delay before pulse
  152. self.windead = 0. # FD window filter dead time
  153. self.pulseType = -1
  154. self.transFreq = -1
  155. self.maxBusV = -1
  156. self.pulseLength = -1
  157. self.interpulseDelay = -1 # for T2, Spin Echo
  158. self.repetitionDelay = -1 # delay between first pulse
  159. self.nPulseMoments = -1 # Number of pulse moments per stack
  160. self.TuneCapacitance = -1 # tuning capac in uF
  161. self.nTransVersion = -1 # Transmitter version
  162. self.nDAQVersion = -1 # DAQ software version
  163. self.nInterleaves = -1 # num interleaves
  164. # self.nReceiveChannels = 4 # Num receive channels
  165. self.RotatedAmplitude = False
  166. # self.DATA = np.zeros(1) # Numpy array to hold all data, dimensions resized based on experiment
  167. # self.PULSES = np.zeros(1) # Numpy array to hold all data, dimensions resized based on experiment
  168. def Print(self):
  169. print ("pulse type", self.pulseType)
  170. print ("maxBusV", self.maxBusV)
  171. print ("inner pulse delay", self.interpulseDelay)
  172. print ("tuning capacitance", self.TuneCapacitance)
  173. print ("sampling rate", self.samp)
  174. print ("dt", self.dt)
  175. print ("dead time", self.deadTime)
  176. print ("pre pulse delay", self.prePulseDelay)
  177. print ("number of pulse moments", self.nPulseMoments)
  178. print ("pulse Length", self.pulseLength)
  179. print ("trans freq", self.transFreq)
  180. def readHeaderFile(self, FileName):
  181. HEADER = np.loadtxt(FileName)
  182. pulseTypeDict = {
  183. 1 : lambda: "FID",
  184. 2 : lambda: "T1",
  185. 3 : lambda: "SPINECHO",
  186. 4 : lambda: "4PhaseT1"
  187. }
  188. pulseLengthDict = {
  189. 1 : lambda x: np.ones(1) * x,
  190. 2 : lambda x: np.ones(2) * x,
  191. 3 : lambda x: np.array([x, 2.*x]),
  192. 4 : lambda x: np.ones(2) * x
  193. }
  194. self.pulseType = pulseTypeDict.get((int)(HEADER[0]))()
  195. self.transFreq = HEADER[1]
  196. self.maxBusV = HEADER[2]
  197. self.pulseLength = pulseLengthDict.get((int)(HEADER[0]))(1e-3*HEADER[3])
  198. self.interpulseDelay = 1e-3*HEADER[4] # for T2, Spin Echo
  199. self.repetitionDelay = HEADER[5] # delay between first pulse
  200. self.nPulseMoments = (int)(HEADER[6]) # Number of pulse moments per stack
  201. self.TuneCapacitance = HEADER[7] # tuning capacitance in uF
  202. self.nTransVersion = HEADER[8] # Transmitter version
  203. self.nDAQVersion = HEADER[9] # DAQ software version
  204. self.nInterleaves = HEADER[10] # num interleaves
  205. self.gain()
  206. # default
  207. self.samp = 50000. # sampling frequency
  208. self.dt = 2e-5 # sampling rate
  209. # newer header files contain 64 entries
  210. if self.nDAQVersion >= 2:
  211. #self.deadtime = HEADER[11]
  212. #self.unknown = HEADER[12]
  213. #self.PreAmpGain = HEADER[13]
  214. self.samp = HEADER[14] # sampling frequency
  215. self.dt = 1./self.samp # sampling rate
  216. self.deadTime = .0055 # instrument dead time before measurement
  217. self.prePulseDelay = 0.05 # delay before pulse
  218. #exit()
  219. def gain(self):
  220. #######################################################
  221. # Circuit gain
  222. # From MRSMatlab
  223. w = 2*np.pi*self.transFreq
  224. # 1e6 due to uF of reported capacitance
  225. L_coil = 1e6/(self.TuneCapacitance*(w**2))
  226. R_coil = 1.
  227. Z1_in = .5 + 1j*.5*w
  228. Z2_in = 1./(1j*w*.000001616)
  229. Z_eq_inv = (1./Z1_in) + (1./Z2_in)
  230. Zeq = 1./Z_eq_inv
  231. Zsource = R_coil + 1j*w*L_coil
  232. voltage_in = Zeq / (Zsource + Zeq)
  233. self.circuitGain = np.abs(voltage_in)
  234. self.circuitPhase_deg = (180/np.pi)+np.angle(voltage_in)
  235. circuitImpedance_ohms = np.abs(Zsource + Zeq)
  236. ######################################################
  237. # PreAmp gain
  238. if self.nTransVersion == 4:
  239. self.PreAmpGain = 1000.
  240. elif self.nTransVersion == 1 or self.nTransVersion == 2 or self.nTransVersion == 3 or self.nTransVersion == 6:
  241. self.PreAmpGain = 500.
  242. else:
  243. print ("unsupported transmitter version")
  244. exit(1)
  245. # Total Receiver Gain
  246. self.RxGain = self.circuitGain * self.PreAmpGain
  247. #####################################################
  248. # Current gain
  249. if floor(self.nDAQVersion) == 1:
  250. self.CurrentGain = 150.
  251. elif floor(self.nDAQVersion) == 2:
  252. self.CurrentGain = 180.
  253. def updateProgress(self):
  254. pass
  255. def TDSmartStack(self, outlierTest, MADcutoff, canvas):
  256. Stack = {}
  257. # align for stacking and modulate
  258. for pulse in self.DATADICT["PULSES"]:
  259. stack = np.zeros(( len(self.DATADICT[pulse]["chan"]), self.DATADICT["nPulseMoments"],\
  260. len(self.DATADICT["stacks"]), len(self.DATADICT[pulse]["TIMES"]) ))
  261. for ipm in range(self.DATADICT["nPulseMoments"]):
  262. istack = 0
  263. for sstack in self.DATADICT["stacks"]:
  264. if self.pulseType == "FID" or pulse == "Pulse 2":
  265. mod = (-1)**(ipm%2) * (-1)**(sstack%2)
  266. elif self.pulseType == "4PhaseT1":
  267. mod = (-1)**(ipm%2) * (-1)**(((sstack-1)/2)%2)
  268. ichan = 0
  269. for chan in self.DATADICT[pulse]["chan"]:
  270. stack[ichan,ipm,istack,:] += mod*self.DATADICT[pulse][chan][ipm][sstack]
  271. ichan += 1
  272. istack += 1
  273. Stack[pulse] = stack
  274. #########################################
  275. # simple stack and plot of simple stack #
  276. #########################################
  277. canvas.reAxH2(np.shape(stack)[0], False, False)
  278. axes = canvas.fig.axes
  279. SimpleStack = {}
  280. VarStack = {}
  281. for pulse in self.DATADICT["PULSES"]:
  282. SimpleStack[pulse] = {}
  283. VarStack[pulse] = {}
  284. ichan = 0
  285. for chan in self.DATADICT[pulse]["chan"]:
  286. SimpleStack[pulse][chan] = 1e9*np.average( Stack[pulse][ichan], 1 )
  287. VarStack[pulse][chan] = 1e9*np.std( Stack[pulse][ichan], 1 )
  288. ax1 = axes[ 2*ichan ]
  289. #ax1.get_yaxis().get_major_formatter().set_useOffset(False)
  290. y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
  291. ax1.yaxis.set_major_formatter(y_formatter)
  292. ax1.plot( 1e3*self.DATADICT[pulse]["TIMES"], np.average( SimpleStack[pulse][chan], 0 ), color='darkblue' )
  293. ax1.set_title("Ch." + str(chan) + ": avg FID", fontsize=8)
  294. ax1.set_xlabel(r"time (ms)", fontsize=8)
  295. if ichan == 0:
  296. ax1.set_ylabel(r"signal [nV]", fontsize=8)
  297. else:
  298. plt.setp(ax1.get_yticklabels(), visible=False)
  299. plt.setp(ax1.get_yaxis().get_offset_text(), visible=False)
  300. # if ichan == 1:
  301. # canvas.ax2.plot( 1e3*self.DATADICT[pulse]["TIMES"], np.average( SimpleStack[pulse][chan], 0 ), color='darkblue' )
  302. # canvas.ax2.set_title("Ch." + str(chan) + ": total average FID", fontsize=8)
  303. # canvas.ax2.set_xlabel(r"time [ms]", fontsize=8)
  304. # if ichan == 2:
  305. # canvas.ax3.plot( 1e3*self.DATADICT[pulse]["TIMES"], np.average( SimpleStack[pulse][chan], 0 ), color='darkblue' )
  306. # canvas.ax3.set_title("Ch." + str(chan) + ": total average FID", fontsize=8)
  307. # canvas.ax3.set_xlabel(r"time [ms]", fontsize=8)
  308. # if ichan == 3:
  309. # canvas.ax4.plot( 1e3*self.DATADICT[pulse]["TIMES"], np.average( SimpleStack[pulse][chan], 0 ), color='darkblue' )
  310. # canvas.ax4.set_title("Ch." + str(chan) + ": total average FID", fontsize=8)
  311. # canvas.ax4.set_xlabel(r"time [ms]", fontsize=8)
  312. ichan += 1
  313. #########################
  314. # Oulier rejectig stack #
  315. #########################
  316. if outlierTest == "MAD":
  317. MADStack = {}
  318. VarStack = {}
  319. #1.4826 is assumption of gaussian noise
  320. madstack = np.zeros(( len(self.DATADICT[pulse]["chan"]),\
  321. self.DATADICT["nPulseMoments"], len(self.DATADICT[pulse]["TIMES"]) ))
  322. varstack = np.zeros(( len(self.DATADICT[pulse]["chan"]),\
  323. self.DATADICT["nPulseMoments"], len(self.DATADICT[pulse]["TIMES"]) ))
  324. for pulse in self.DATADICT["PULSES"]:
  325. MADStack[pulse] = {}
  326. VarStack[pulse] = {}
  327. ichan = 0
  328. for chan in self.DATADICT[pulse]["chan"]:
  329. ax1 = axes[ 2*ichan ]
  330. for ipm in range(self.DATADICT["nPulseMoments"]):
  331. # # brutal loop over time, can this be vectorized?
  332. # for it in range(len(self.DATADICT[pulse]["TIMES"])):
  333. # x = 1e9 *Stack[pulse][ichan,ipm,:,it]
  334. # MAD = 1.4826 * np.median( np.abs(x-np.median(x)) )
  335. # good = 0
  336. # for istack in self.DATADICT["stacks"]:
  337. # if (np.abs(x[istack-1]-np.median(x))) / MAD < 2:
  338. # good += 1
  339. # madstack[ ichan, ipm, it ] += x[istack-1]
  340. # else:
  341. # pass
  342. # madstack[ichan, ipm, it] /= good
  343. # percent = int(1e2* (float)(ipm) / (float)(self.DATADICT["nPulseMoments"]) )
  344. # self.progressTrigger.emit(percent)
  345. # Vectorized version of above...much, much faster
  346. x = 1e9*copy.deepcopy(Stack[pulse][ichan][ipm,:,:]) # stack and time indices
  347. tile_med = np.tile( np.median(x, axis=0), (np.shape(x)[0],1))
  348. MAD = MADcutoff * np.median(np.abs(x - tile_med), axis=0)
  349. tile_MAD = np.tile( MAD, (np.shape(x)[0],1))
  350. good = np.abs(x-tile_med)/tile_MAD < 2. # 1.4826 # 2
  351. madstack[ichan][ipm] = copy.deepcopy( np.ma.masked_array(x, good != True).mean(axis=0) )
  352. varstack[ichan][ipm] = copy.deepcopy( np.ma.masked_array(x, good != True).std(axis=0) )
  353. # reporting
  354. percent = int(1e2* (float)((ipm)+ichan*self.DATADICT["nPulseMoments"]) /
  355. (float)(self.DATADICT["nPulseMoments"] * len(self.DATADICT[pulse]["chan"])))
  356. self.progressTrigger.emit(percent)
  357. ax1.plot( 1e3*self.DATADICT[pulse]["TIMES"], np.average( madstack[ichan], 0 ) , color='darkred')
  358. MADStack[pulse][chan] = madstack[ichan]
  359. VarStack[pulse][chan] = varstack[ichan]
  360. ichan += 1
  361. self.DATADICT["stack"] = MADStack
  362. else:
  363. self.DATADICT["stack"] = SimpleStack
  364. #########################################
  365. # Plot Fourier Transform representation #
  366. #########################################
  367. # canvas.fig.subplots_adjust(right=0.8)
  368. # cbar_ax = canvas.fig.add_axes([0.85, 0.1, 0.015, 0.355])
  369. # cbar_ax.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  370. im2 = []
  371. for pulse in self.DATADICT["PULSES"]:
  372. ichan = 0
  373. axes = canvas.fig.axes
  374. vvmin = 1e10
  375. vvmax = 0
  376. for chan in self.DATADICT[pulse]["chan"]:
  377. ax1 = axes[2*ichan ]
  378. ax2 = axes[2*ichan+1] # TODO fix hard coded number
  379. if outlierTest == "MAD":
  380. X = np.fft.rfft( MADStack[pulse][chan][0,:] )
  381. nu = np.fft.fftfreq(len( MADStack[pulse][chan][0,:]), d=self.dt)
  382. else:
  383. X = np.fft.rfft( SimpleStack[pulse][chan][0,:] )
  384. nu = np.fft.fftfreq(len( SimpleStack[pulse][chan][0,:]), d=self.dt)
  385. nu = nu[0:len(X)]
  386. nu[-1] = np.abs(nu[-1])
  387. df = nu[1] - nu[0]
  388. of = 0
  389. istart = int((self.transFreq-150.)/df)
  390. iend = int((self.transFreq+150.)/df)
  391. of = nu[istart]
  392. def freqlabel(xxx, pos):
  393. return '%1.0f' %(of + xxx*df)
  394. formatter = FuncFormatter(freqlabel)
  395. SFFT = np.zeros( (self.DATADICT["nPulseMoments"], len(X)), dtype=np.complex64 )
  396. SFFT[0,:] = X
  397. for ipm in range(1, self.DATADICT["nPulseMoments"]):
  398. if outlierTest == "MAD":
  399. SFFT[ipm,:] = np.fft.rfft( MADStack[pulse][chan][ipm,:] )
  400. else:
  401. SFFT[ipm,:] = np.fft.rfft( SimpleStack[pulse][chan][ipm,:] )
  402. # convert to dB and add colorbars
  403. #db = 20.*np.log10(np.abs(SFFT[:,istart:iend]))
  404. db = (np.abs(SFFT[:,istart:iend]))
  405. vvmin = min(vvmin, np.min (db))
  406. vvmax = max(vvmax, np.max (db))
  407. im2.append(ax2.matshow( db, aspect='auto', cmap=cmocean.cm.ice, vmin=vvmin, vmax=vvmax))
  408. #im2 = ax2.matshow( db, aspect='auto', cmap=cmocean.cm.ice, vmin=vvmin, vmax=vvmax)
  409. if ichan == 0:
  410. ax2.set_ylabel(r"$q$ (A $\cdot$ s)", fontsize=8)
  411. else:
  412. #ax2.yaxis.set_ticklabels([])
  413. plt.setp(ax2.get_yticklabels(), visible=False)
  414. ax2.xaxis.set_major_formatter(formatter)
  415. ax2.xaxis.set_ticks_position('bottom')
  416. ax2.xaxis.set_major_locator(MaxNLocator(3))
  417. y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
  418. ax2.yaxis.set_major_formatter(y_formatter)
  419. #if chan == self.DATADICT[pulse]["chan"][-1]:
  420. #cb2 = canvas.fig.colorbar(im2, cax=cbar_ax, format='%1.0e')
  421. #cb2 = canvas.fig.colorbar(im2[0], ax=ax2, format='%1.0e', orientation='horizontal')
  422. #cb2 = canvas.fig.colorbar(im2, ax=ax2, format='%1.0e', orientation='horizontal')
  423. #cb2.ax.tick_params(axis='both', which='major', labelsize=8)
  424. #cb2.set_label("signal (dB)", fontsize=8)
  425. ichan += 1
  426. canvas.fig.subplots_adjust(hspace=.1, wspace=.05, left=.075, right=.95 )#left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
  427. #cb1 = canvas.fig.colorbar(im, ax=axes[0::2], format='%1.0e', orientation='horizontal', shrink=.35, aspect=30)
  428. #cb1.ax.tick_params(axis='both', which='major', labelsize=8)
  429. #cb1.set_label("$\mathcal{V}_N$ (nV)", fontsize=8)
  430. cb2 = canvas.fig.colorbar(im2[-1], ax=axes[1::2], format='%1.0e', orientation='horizontal', shrink=.35, aspect=30)
  431. cb2.ax.tick_params(axis='both', which='major', labelsize=8)
  432. cb2.set_label("$\mathcal{V}_N$ (nV)", fontsize=8)
  433. #canvas.fig.tight_layout()
  434. canvas.draw()
  435. self.doneTrigger.emit()
  436. def sumData(self, canvas, fred):
  437. chans = copy.deepcopy(self.DATADICT[self.DATADICT["PULSES"][0]]["chan"]) #= np.array( ( self.DATADICT[pulse]["chan"][0], ) )
  438. nchan = len(chans)
  439. # Sum permutations of two channel combos
  440. for ich in range(nchan-1):
  441. for ch in chans[ich+1:]:
  442. chsum = chans[ich] + "+" + ch
  443. for pulse in self.DATADICT["PULSES"]:
  444. self.DATADICT[pulse][chsum] = {}
  445. for ipm in range(self.DATADICT["nPulseMoments"]):
  446. self.DATADICT[pulse][chsum][ipm] = {}
  447. for istack in self.DATADICT["stacks"]:
  448. self.DATADICT[pulse][chsum][ipm][istack] = self.DATADICT[pulse][chans[ich]][ipm][istack] + self.DATADICT[pulse][ch][ipm][istack]
  449. self.DATADICT[pulse]["chan"].append(chsum)
  450. # Sum all channels
  451. chsum = ""
  452. for ch in chans:
  453. chsum += ch + "+"
  454. chsum = chsum[0:-1] # remove last "+"
  455. for pulse in self.DATADICT["PULSES"]:
  456. self.DATADICT[pulse][chsum] = {}
  457. for ipm in range(self.DATADICT["nPulseMoments"]):
  458. self.DATADICT[pulse][chsum][ipm] = {}
  459. for istack in self.DATADICT["stacks"]:
  460. self.DATADICT[pulse][chsum][ipm][istack] = copy.deepcopy(self.DATADICT[pulse][chans[0]][ipm][istack])
  461. for ch in chans[1:]:
  462. self.DATADICT[pulse][chsum][ipm][istack] += self.DATADICT[pulse][ch][ipm][istack]
  463. self.DATADICT[pulse]["chan"].append(chsum)
  464. # if nchan > 2:
  465. # for ch in chans:
  466. # chsum += ch
  467. # for ch2 in chans[1::]:
  468. # for pulse in self.DATADICT["PULSES"]:
  469. # self.DATADICT[pulse][chsum] = {}
  470. # for istack in self.DATADICT["stacks"]:
  471. # self.DATADICT[pulse][chsum][ipm][istack] = self.DATADICT[pulse][chans[ich]][ipm][istack] + self.DATADICT[pulse][ch][ipm][istack]
  472. self.doneTrigger.emit()
  473. def quadDet(self, clip, phase, canvas):
  474. from scipy import signal
  475. self.RotatedAmplitude = True
  476. wL = self.transFreq * 2*np.pi
  477. vL = self.transFreq
  478. #T = 50
  479. dt = self.dt
  480. #DT = 0.01
  481. CA = {} # corrected amplitude
  482. IP = {} # instantaneous phase
  483. NR = {} # Noise residual
  484. RE = {} # Real channel
  485. IM = {} # Imaginary channel
  486. # global maximums for plotting
  487. CAmax = {}
  488. NRmax = {}
  489. REmax = {}
  490. IMmax = {}
  491. E0,phi,df,T2 = 100.,0,0,.2
  492. first = False
  493. self.sigma = {}
  494. for pulse in self.DATADICT["PULSES"]:
  495. CA[pulse] = {}
  496. IP[pulse] = {}
  497. NR[pulse] = {}
  498. RE[pulse] = {}
  499. IM[pulse] = {}
  500. CAmax[pulse] = 0
  501. NRmax[pulse] = 0
  502. REmax[pulse] = 0
  503. IMmax[pulse] = 0
  504. ichan = 0
  505. self.sigma[pulse] = {}
  506. for chan in self.DATADICT[pulse]["chan"]:
  507. CA[pulse][chan] = np.zeros( (self.DATADICT["nPulseMoments"], len(self.DATADICT[pulse]["TIMES"])-clip ) )
  508. IP[pulse][chan] = np.zeros( (self.DATADICT["nPulseMoments"], len(self.DATADICT[pulse]["TIMES"])-clip ) )
  509. NR[pulse][chan] = np.zeros( (self.DATADICT["nPulseMoments"], len(self.DATADICT[pulse]["TIMES"])-clip ) )
  510. RE[pulse][chan] = np.zeros( (self.DATADICT["nPulseMoments"], len(self.DATADICT[pulse]["TIMES"])-clip ) )
  511. IM[pulse][chan] = np.zeros( (self.DATADICT["nPulseMoments"], len(self.DATADICT[pulse]["TIMES"])-clip ) )
  512. for ipm in range(0, self.DATADICT["nPulseMoments"]):
  513. #t = self.DATADICT[pulse]["TIMES"] - self.DATADICT[pulse]["PULSE_TIMES"][-1]
  514. xn = self.DATADICT["stack"][pulse][chan][ipm,:]
  515. ht = signal.hilbert(xn)*np.exp(-1j*wL*self.DATADICT[pulse]["TIMES"])
  516. #############################################################
  517. # Quadrature signal
  518. RE[pulse][chan][ipm,:] = np.real(ht[clip::])
  519. IM[pulse][chan][ipm,:] = np.imag(ht[clip::])
  520. REmax[pulse] = max(REmax[pulse], np.max(np.real(ht[clip::])))
  521. IMmax[pulse] = max(IMmax[pulse], np.max(np.imag(ht[clip::])))
  522. #############################################################
  523. # Instantaneous phase
  524. IP[pulse][chan][ipm,:] = np.angle(ht)[clip::]
  525. #############################################################
  526. # Rotated amplitude
  527. #if ipm != 0:
  528. [success, E0, df, phi, T2] = decay.quadratureDetect2( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"], (E0,phi,df,T2))
  529. #[ E0, df, phi, T2] = decay.quadratureDetect( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"] )
  530. #else:
  531. # [success, E0, df, phi, T2] = decay.quadratureDetect2( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"])
  532. #[success, E0, df, phi, T2] = decay.quadratureDetect( ht.real, ht.imag, self.DATADICT[pulse]["TIMES"] )
  533. print("success", success, "E0", E0, "phi", phi, "df", df, "T2", T2)
  534. D = self.RotateAmplitude( ht.real, ht.imag, phi, df, self.DATADICT[pulse]["TIMES"] )
  535. CA[pulse][chan][ipm,:] = D.imag[clip::] # amplitude data
  536. NR[pulse][chan][ipm,:] = D.real[clip::] # noise data
  537. CAmax[pulse] = max(CAmax[pulse], np.max(D.imag[clip::]) )
  538. NRmax[pulse] = max(NRmax[pulse], np.max(D.real[clip::]) )
  539. self.sigma[pulse][chan] = np.std(NR[pulse][chan])
  540. # reporting
  541. percent = int(1e2* (float)((ipm)+ichan*self.DATADICT["nPulseMoments"]) /
  542. (float)(self.DATADICT["nPulseMoments"] * len(self.DATADICT[pulse]["chan"])))
  543. self.progressTrigger.emit(percent)
  544. ichan += 1
  545. self.DATADICT["CA"] = CA
  546. self.DATADICT["IP"] = IP
  547. self.DATADICT["NR"] = NR
  548. self.DATADICT["RE"] = RE
  549. self.DATADICT["IM"] = IM
  550. self.DATADICT["CAmax"] = CAmax
  551. self.DATADICT["NRmax"] = NRmax
  552. self.DATADICT["REmax"] = REmax
  553. self.DATADICT["IMmax"] = IMmax
  554. self.doneTrigger.emit()
  555. def plotQuadDet(self, clip, phase, canvas):
  556. canvas.reAxH2( len(self.DATADICT[ self.DATADICT["PULSES"][0] ]["chan"] ), False, False)
  557. ###############
  558. # Plot on GUI #
  559. ###############
  560. dcmap = cmocean.cm.balance_r #"RdBu" #YlGn" # "coolwarm_r" # diverging
  561. canvas.reAxH2( len(self.DATADICT[ self.DATADICT["PULSES"][0] ]["chan"] ), False, False)
  562. for pulse in self.DATADICT["PULSES"]:
  563. ichan = 0
  564. axes = canvas.fig.axes
  565. mmaxr = 0.
  566. mmaxi = 0.
  567. if clip > 0:
  568. time_sp = 1e3 * (self.DATADICT[pulse]["TIMES"][clip-1::] - self.DATADICT[pulse]["PULSE_TIMES"][-1] )
  569. else:
  570. time_sp = 1e3 * (self.DATADICT[pulse]["TIMES"] - self.DATADICT[pulse]["PULSE_TIMES"][-1] )
  571. QQ = np.average(self.DATADICT[pulse]["Q"], axis=1 )
  572. for chan in self.DATADICT[pulse]["chan"]:
  573. ax1 = axes[2*ichan ]
  574. ax2 = axes[2*ichan+1] # TODO fix hard coded number
  575. if phase == 0: # Re Im
  576. im1 = ax1.pcolormesh( time_sp, QQ, self.DATADICT["RE"][pulse][chan], cmap=dcmap, rasterized=True,\
  577. vmin=-self.DATADICT["REmax"][pulse] , vmax=self.DATADICT["REmax"][pulse] )
  578. im2 = ax2.pcolormesh( time_sp, QQ, self.DATADICT["IM"][pulse][chan], cmap=dcmap, rasterized=True,\
  579. vmin=-self.DATADICT["IMmax"][pulse], vmax=self.DATADICT["IMmax"][pulse] )
  580. if phase == 1: # Amp phase
  581. im1 = ax1.pcolormesh( time_sp, QQ, self.DATADICT["CA"][pulse][chan], cmap=dcmap, rasterized=True,
  582. vmin=-self.DATADICT["CAmax"][pulse] , vmax=self.DATADICT["CAmax"][pulse] )
  583. im2 = ax2.pcolormesh( time_sp, QQ, self.DATADICT["IP"][pulse][chan], cmap=cmocean.cm.phase, rasterized=True,\
  584. vmin=-np.pi, vmax=np.pi)
  585. if phase == 2: # CA NR
  586. im1 = ax1.pcolormesh( time_sp, QQ, self.DATADICT["CA"][pulse][chan], cmap=dcmap, rasterized=True,\
  587. vmin=-self.DATADICT["CAmax"][pulse] , vmax=self.DATADICT["CAmax"][pulse] )
  588. im2 = ax2.pcolormesh( time_sp, QQ, self.DATADICT["NR"][pulse][chan], cmap=dcmap, rasterized=True,
  589. vmin=-self.DATADICT["NRmax"][pulse] , vmax=self.DATADICT["NRmax"][pulse] )
  590. # cb2 = canvas.fig.colorbar(im2, ax=ax2, format='%1.0e')
  591. # cb2.set_label("Noise residual (nV)", fontsize=8)
  592. # cb2.ax.tick_params(axis='both', which='major', labelsize=8)
  593. # cb1 = canvas.fig.colorbar(im1, ax=ax1, format='%1.0e')
  594. # cb1.set_label("Phased amplitude (nV)", fontsize=8)
  595. # cb1.ax.tick_params(axis='both', which='major', labelsize=8)
  596. # cb2 = canvas.fig.colorbar(im2, ax=ax2, format="%1.0e")
  597. # cb2.set_label("Phase (rad)", fontsize=8)
  598. # cb2.ax.tick_params(axis='both', which='major', labelsize=8)
  599. # cb1 = canvas.fig.colorbar(im1, ax=ax1, format="%1.0e")
  600. # cb1.set_label("FID (nV)", fontsize=8)
  601. # cb1.ax.tick_params(axis='both', which='major', labelsize=8)
  602. # if you save these as pdf or eps, there are artefacts
  603. # for cbar in [cb1,cb2]:
  604. # #cbar.solids.set_rasterized(True)
  605. # cbar.solids.set_edgecolor("face")
  606. # reporting
  607. percent = int(1e2* (float)(ichan)/len(self.DATADICT[pulse]["chan"]))
  608. self.progressTrigger.emit(percent)
  609. if ichan == 0:
  610. ax1.set_ylabel(r"$q$ ( $\mathrm{A}\cdot\mathrm{s}$)", fontsize=8)
  611. ax2.set_ylabel(r"$q$ ( $\mathrm{A}\cdot\mathrm{s}$)", fontsize=8)
  612. else:
  613. #ax2.yaxis.set_ticklabels([])
  614. #ax1.yaxis.set_ticklabels([])
  615. plt.setp(ax1.get_yticklabels(), visible=False)
  616. plt.setp(ax2.get_yticklabels(), visible=False)
  617. ichan += 1
  618. ax1.set_yscale('log')
  619. ax2.set_yscale('log')
  620. plt.setp(ax1.get_xticklabels(), visible=False)
  621. ax1.set_ylim( np.min(QQ), np.max(QQ) )
  622. ax2.set_ylim( np.min(QQ), np.max(QQ) )
  623. ax1.set_xlim( np.min(time_sp), np.max(time_sp) )
  624. ax2.set_xlim( np.min(time_sp), np.max(time_sp) )
  625. #ax2.set_xlabel(r"Time since end of pulse (ms)", fontsize=8)
  626. ax2.set_xlabel(r"Time (ms)", fontsize=8)
  627. canvas.fig.subplots_adjust(hspace=.15, wspace=.05, left=.075, right=.95, bottom=.1, top=.95 )#left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
  628. tick_locator = MaxNLocator(nbins=5)
  629. cb1 = canvas.fig.colorbar(im1, ax=axes[0::2], format='%1.0e', orientation='horizontal', shrink=.35, aspect=30)
  630. cb1.ax.tick_params(axis='both', which='major', labelsize=8)
  631. cb1.set_label("$\mathcal{V}_N$ (nV)", fontsize=8)
  632. cb1.locator = tick_locator
  633. cb1.update_ticks()
  634. cb2 = canvas.fig.colorbar(im2, ax=axes[1::2], format='%1.0e', orientation='horizontal', shrink=.35, aspect=30, pad=.2)
  635. cb2.ax.tick_params(axis='both', which='major', labelsize=8)
  636. cb2.set_label("$\mathcal{V}_N$ (nV)", fontsize=8)
  637. cb2.locator = tick_locator
  638. cb2.update_ticks()
  639. canvas.draw()
  640. self.doneTrigger.emit()
  641. def RotateAmplitude(self, X, Y, zeta, df, t):
  642. V = X + 1j*Y
  643. return np.abs(V) * np.exp( 1j * ( np.angle(V) - zeta - 2.*np.pi*df*t ) )
  644. def gateIntegrate( self, gpd, clip, canvas ):
  645. """ Gate integrate the real, imaginary, phased, and noise residual channels
  646. """
  647. self.gated = True
  648. self.GATED = {}
  649. for pulse in self.DATADICT["PULSES"]:
  650. QQ = np.average(self.DATADICT[pulse]["Q"], axis=1 )
  651. ichan = 0
  652. for chan in self.DATADICT[pulse]["chan"]:
  653. self.GATED[chan] = {}
  654. for ipm in range(0, self.DATADICT["nPulseMoments"]):
  655. # Time since pulse rather than since record starts...
  656. #if clip > 0:
  657. # time_sp = 1e3 * (self.DATADICT[pulse]["TIMES"][clip:] - self.DATADICT[pulse]["PULSE_TIMES"][-1] )
  658. #else:
  659. time_sp = 1e3 * (self.DATADICT[pulse]["TIMES"] - self.DATADICT[pulse]["PULSE_TIMES"][-1] )
  660. #GT, GD, GTT, sig_stack, isum = rotate.gateIntegrate( self.DATADICT["CA"][pulse][chan][ipm,:], time_sp, gpd, self.sigma[pulse][chan], 1.5 )
  661. #GT2, GP, GTT, sig_stack_err, isum = rotate.gateIntegrate( self.DATADICT["NR"][pulse][chan][ipm,:], time_sp, gpd, self.sigma[pulse][chan], 1.5 )
  662. GT, GCA, GTT, sig_stack, isum = rotate.gateIntegrate( self.DATADICT["CA"][pulse][chan][ipm], time_sp, gpd, self.sigma[pulse][chan], 1.5 )
  663. GT, GNR, GTT, sig_stack, isum = rotate.gateIntegrate( self.DATADICT["NR"][pulse][chan][ipm], time_sp, gpd, self.sigma[pulse][chan], 1.5 )
  664. GT, GRE, GTT, sig_stack, isum = rotate.gateIntegrate( self.DATADICT["RE"][pulse][chan][ipm], time_sp, gpd, self.sigma[pulse][chan], 1.5 )
  665. GT, GIM, GTT, sig_stack, isum = rotate.gateIntegrate( self.DATADICT["IM"][pulse][chan][ipm], time_sp, gpd, self.sigma[pulse][chan], 1.5 )
  666. GT, GIP, GTT, sig_stack, isum = rotate.gateIntegrate( self.DATADICT["IP"][pulse][chan][ipm], time_sp, gpd, self.sigma[pulse][chan], 1.5 )
  667. if ipm == 0:
  668. # self.GATED[chan]["DATA"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)) )
  669. # self.GATED[chan]["ERR"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)) )
  670. # self.GATED[chan]["SIGMA"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)) )
  671. self.GATED[chan]["CA"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)-clip) )
  672. self.GATED[chan]["NR"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)-clip) )
  673. self.GATED[chan]["RE"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)-clip) )
  674. self.GATED[chan]["IM"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)-clip) )
  675. self.GATED[chan]["IP"] = np.zeros( ( self.DATADICT["nPulseMoments"], len(GT)-clip) )
  676. self.GATED[chan]["isum"] = isum
  677. #self.GATED[chan]["DATA"][ipm] = GD.real
  678. self.GATEDABSCISSA = GT[clip:]
  679. self.GATEDWINDOW = GTT[clip:]
  680. #self.GATED[chan]["SIGMA"][ipm] = sig_stack #_err # GP.real
  681. #self.GATED[chan]["ERR"][ipm] = GP.real
  682. self.GATED[chan]["CA"][ipm] = GCA.real[clip:]
  683. self.GATED[chan]["NR"][ipm] = GNR.real[clip:]
  684. self.GATED[chan]["RE"][ipm] = GRE.real[clip:]
  685. self.GATED[chan]["IM"][ipm] = GIM.real[clip:]
  686. self.GATED[chan]["IP"][ipm] = GIP.real[clip:]
  687. percent = int(1e2* (float)((ipm)+ichan*self.DATADICT["nPulseMoments"]) /
  688. (float)(self.DATADICT["nPulseMoments"] * len(self.DATADICT[pulse]["chan"])))
  689. self.progressTrigger.emit(percent)
  690. self.GATED[chan]["GTT"] = GTT[clip:]
  691. self.GATED[chan]["GT"] = GT[clip:]
  692. self.GATED[chan]["QQ"] = QQ
  693. ichan += 1
  694. self.doneTrigger.emit()
  695. def bootstrap_resample(self, X, n=None):
  696. # from http://nbviewer.jupyter.org/gist/aflaxman/6871948
  697. """ Bootstrap resample an array_like
  698. Parameters
  699. ----------
  700. X : array_like
  701. data to resample
  702. n : int, optional
  703. length of resampled array, equal to len(X) if n==None
  704. Results
  705. -------
  706. returns X_resamples
  707. """
  708. if n == None:
  709. n = len(X)
  710. resample_i = np.floor(np.random.rand(n)*len(X)).astype(int)
  711. return X[resample_i]
  712. def bootstrap_sigma(self, pulse, chan):
  713. # bootstrap resample
  714. nt = len(self.GATED[chan]["GT"])
  715. nb = 5000
  716. XS = np.zeros( (nb, nt) )
  717. for ii in range(nb):
  718. for it in range(nt):
  719. if self.GATED[chan]["isum"][it] < 8:
  720. XS[ii, it] = self.sigma[pulse][chan]
  721. else:
  722. if it == 0:
  723. X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it], self.GATED[chan]["NR"][:,it+1], \
  724. self.GATED[chan]["NR"][:,it+2], self.GATED[chan]["NR"][:,it+3] ) ), n=nt )
  725. elif it == 1:
  726. X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it-1], self.GATED[chan]["NR"][:,it], \
  727. self.GATED[chan]["NR"][:,it+1], self.GATED[chan]["NR"][:,it+2] ) ), n=nt )
  728. elif it == nt-2:
  729. X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it+1], self.GATED[chan]["NR"][:,it], \
  730. self.GATED[chan]["NR"][:,it-1], self.GATED[chan]["NR"][:,it-2] ) ), n=nt )
  731. elif it == nt-1:
  732. X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it], self.GATED[chan]["NR"][:,it-1], \
  733. self.GATED[chan]["NR"][:,it-2], self.GATED[chan]["NR"][:,it-3] ) ), n=nt )
  734. else:
  735. X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it-2] , self.GATED[chan]["NR"][:,it-1], \
  736. self.GATED[chan]["NR"][:,it], self.GATED[chan]["NR"][:,it+1], self.GATED[chan]["NR"][:,it+2] )), n=nt )
  737. XS[ii,it] = np.std(X)
  738. return XS
  739. def plotGateIntegrate( self, gpd, clip, phase, canvas ):
  740. """ Plot the gate integration
  741. """
  742. canvas.reAxH2( len(self.DATADICT[ self.DATADICT["PULSES"][0] ]["chan"] ), False, False)
  743. axes = canvas.fig.axes
  744. cmap = cmocean.cm.balance_r
  745. # Calculate maximum for plotting...TODO move into loop above
  746. vmax1 = 0
  747. vmax2 = 0
  748. for pulse in self.DATADICT["PULSES"]:
  749. for chan in self.DATADICT[pulse]["chan"]:
  750. if phase == 0:
  751. vmax1 = max(vmax1, np.max(np.abs(self.GATED[chan]["RE"])))
  752. vmax2 = max(vmax2, np.max(np.abs(self.GATED[chan]["IM"])))
  753. elif phase == 1:
  754. vmax1 = max(vmax1, np.max(np.abs(self.GATED[chan]["CA"])))
  755. vmax2 = np.pi
  756. elif phase == 2:
  757. vmax1 = max(vmax1, np.max(np.abs(self.GATED[chan]["CA"])))
  758. vmax2 = max(vmax2, np.max(np.abs(self.GATED[chan]["NR"])))
  759. for pulse in self.DATADICT["PULSES"]:
  760. ichan = 0
  761. for chan in self.DATADICT[pulse]["chan"]:
  762. ax1 = axes[2*ichan ]
  763. ax2 = axes[2*ichan+1]
  764. if phase == 0:
  765. im1 = ax1.pcolormesh(self.GATED[chan]["GTT"], self.GATED[chan]["QQ"], self.GATED[chan]["RE"], cmap=cmap, vmin=-vmax1, vmax=vmax1)
  766. im2 = ax2.pcolormesh(self.GATED[chan]["GTT"], self.GATED[chan]["QQ"], self.GATED[chan]["IM"], cmap=cmap, vmin=-vmax2, vmax=vmax2)
  767. elif phase == 1:
  768. im1 = ax1.pcolormesh(self.GATED[chan]["GTT"], self.GATED[chan]["QQ"], self.GATED[chan]["CA"], cmap=cmap, vmin=-vmax1, vmax=vmax1)
  769. im2 = ax2.pcolormesh(self.GATED[chan]["GTT"], self.GATED[chan]["QQ"], self.GATED[chan]["IP"], cmap=cmocean.cm.phase, vmin=-vmax2, vmax=vmax2)
  770. elif phase == 2:
  771. im1 = ax1.pcolormesh(self.GATED[chan]["GTT"], self.GATED[chan]["QQ"], self.GATED[chan]["CA"], cmap=cmap, vmin=-vmax1, vmax=vmax1)
  772. XS = self.bootstrap_sigma(pulse, chan)
  773. #im2 = ax2.pcolormesh(self.GATED[chan]["GTT"], self.GATED[chan]["QQ"], self.GATED[chan]["NR"], cmap=cmap, vmin=-vmax2, vmax=vmax2)
  774. # bootstrap resample
  775. # nt = len(self.GATED[chan]["GT"])
  776. # nb = 5000
  777. # XS = np.zeros( (nb, nt) )
  778. # for ii in range(nb):
  779. # #XS = []
  780. # for it in range(nt):
  781. # if self.GATED[chan]["isum"][it] < 8:
  782. # XS[ii, it] = self.sigma[pulse][chan]
  783. # else:
  784. # if it == 0:
  785. # X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it], self.GATED[chan]["NR"][:,it+1], \
  786. # self.GATED[chan]["NR"][:,it+2], self.GATED[chan]["NR"][:,it+3] ) ), n=nt )
  787. # if it == 1:
  788. # X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it-1], self.GATED[chan]["NR"][:,it], \
  789. # self.GATED[chan]["NR"][:,it+1], self.GATED[chan]["NR"][:,it+2] ) ), n=nt )
  790. # elif it == nt-2:
  791. # X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it+1], self.GATED[chan]["NR"][:,it], \
  792. # self.GATED[chan]["NR"][:,it-1], self.GATED[chan]["NR"][:,it-2] ) ), n=nt )
  793. # elif it == nt-1:
  794. # X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it], self.GATED[chan]["NR"][:,it-1], \
  795. # self.GATED[chan]["NR"][:,it-2], self.GATED[chan]["NR"][:,it-3] ) ), n=nt )
  796. # else:
  797. # X = self.bootstrap_resample( np.concatenate( (self.GATED[chan]["NR"][:,it-2] , self.GATED[chan]["NR"][:,it-1], \
  798. # self.GATED[chan]["NR"][:,it], self.GATED[chan]["NR"][:,it+1], self.GATED[chan]["NR"][:,it+2] )), n=nt )
  799. # XS[ii,it] = np.std(X)
  800. #if ii == 0:
  801. # ax2.plot( self.GATED[chan]["GT"], XS[ii], '-', linewidth=1, markersize=4, alpha=.5, color='lightgrey', label = "bootstrap sim" )
  802. #else:
  803. # ax2.plot( self.GATED[chan]["GT"], XS[ii], '-', linewidth=1, markersize=4, alpha=.5, color='lightgrey' )
  804. ax2.plot( self.GATED[chan]["GT"], np.std(self.GATED[chan]["NR"], axis=0), color='darkgrey', linewidth=2, label="gate std" )
  805. ax2.plot( np.tile(self.GATED[chan]["GT"], (5000,1) ), XS, '.', color='lightgrey', linewidth=1, alpha=.5 )
  806. ax2.plot( self.GATED[chan]["GT"], np.average(XS, axis=0), color='black', linewidth=2, label="bootstrap avg." )
  807. ax2.plot( self.GATED[chan]["GT"], np.median(XS, axis=0), color='black', linewidth=2, label="bootstrap med." )
  808. ax2.legend()
  809. im1.set_edgecolor('face')
  810. if phase != 2:
  811. im2.set_edgecolor('face')
  812. plt.setp(ax1.get_xticklabels(), visible=False)
  813. ax1.set_ylim( np.min(self.GATED[chan]["QQ"]), np.max(self.GATED[chan]["QQ"]) )
  814. if phase != 2:
  815. ax2.set_ylim( np.min(self.GATED[chan]["QQ"]), np.max(self.GATED[chan]["QQ"]) )
  816. ax1.set_xlim( np.min(self.GATED[chan]["GTT"]), np.max(self.GATED[chan]["GTT"]) )
  817. ax2.set_xlim( np.min(self.GATED[chan]["GTT"]), np.max(self.GATED[chan]["GTT"]) )
  818. ax1.set_yscale('log')
  819. ax2.set_yscale('log')
  820. qlabs = np.append(np.concatenate( ( self.GATED[chan]["QQ"][0:1], self.GATED[chan]["QQ"][9::10] )), self.GATED[chan]["QQ"][-1] )
  821. ax1.yaxis.set_ticks( qlabs ) # np.append(np.concatenate( (QQ[0:1],QQ[9::10] )), QQ[-1] ) )
  822. if phase != 2:
  823. ax2.yaxis.set_ticks( qlabs ) #np.append(np.concatenate( (QQ[0:1],QQ[9::10] )), QQ[-1] ) )
  824. #formatter = matplotlib.ticker.LogFormatter(10, labelOnlyBase=False)
  825. formatter = matplotlib.ticker.FuncFormatter(lambda x, pos: str((round(x,1))))
  826. ax1.yaxis.set_major_formatter(formatter) #matplotlib.ticker.FormatStrFormatter('%d.1'))
  827. ax2.yaxis.set_major_formatter(formatter) #matplotlib.ticker.FormatStrFormatter('%d.1'))
  828. ax1.xaxis.set_major_formatter(formatter) #matplotlib.ticker.FormatStrFormatter('%d.1'))
  829. ax2.xaxis.set_major_formatter(formatter) #matplotlib.ticker.FormatStrFormatter('%d.1'))
  830. ax1.set_xscale('log')
  831. ax2.set_xscale('log')
  832. if ichan == 0:
  833. ax1.set_ylabel(r"$q$ ( $\mathrm{A}\cdot\mathrm{s}$)", fontsize=8)
  834. if phase == 2:
  835. ax2.set_ylabel(r"noise est. (nV)", fontsize=8)
  836. else:
  837. ax2.set_ylabel(r"$q$ ( $\mathrm{A}\cdot\mathrm{s}$)", fontsize=8)
  838. else:
  839. plt.setp(ax1.get_yticklabels(), visible=False)
  840. plt.setp(ax2.get_yticklabels(), visible=False)
  841. ax2.set_xlabel(r"$t-\tau_p$ (ms)", fontsize=8)
  842. ichan += 1
  843. #canvas.fig.subplots_adjust(hspace=.1, wspace=.05, left=.075, right=.925 )#left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
  844. #canvas.fig.tight_layout()
  845. #canvas.draw()
  846. canvas.fig.subplots_adjust(hspace=.15, wspace=.05, left=.075, right=.95, bottom=.1, top=.95 )#left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
  847. tick_locator = MaxNLocator(nbins=5)
  848. cb1 = canvas.fig.colorbar(im1, ax=axes[0::2], format='%1.0e', orientation='horizontal', shrink=.35, aspect=30)
  849. cb1.ax.tick_params(axis='both', which='major', labelsize=8)
  850. cb1.set_label("$\mathcal{V}_N$ (nV)", fontsize=8)
  851. cb1.locator = tick_locator
  852. cb1.update_ticks()
  853. if phase != 2:
  854. cb2 = canvas.fig.colorbar(im2, ax=axes[1::2], format='%1.0e', orientation='horizontal', shrink=.35, aspect=30, pad=.2)
  855. cb2.ax.tick_params(axis='both', which='major', labelsize=8)
  856. cb2.set_label("$\mathcal{V}_N$ (nV)", fontsize=8)
  857. cb2.locator = tick_locator
  858. cb2.update_ticks()
  859. canvas.draw()
  860. self.doneTrigger.emit()
  861. def FDSmartStack(self, cv, canvas):
  862. from matplotlib.colors import LogNorm
  863. from matplotlib.ticker import MaxNLocator
  864. """
  865. Currently this stacks 4-phase second pulse data only, we need to generalise
  866. """
  867. try:
  868. canvas.fig.clear()
  869. except:
  870. pass
  871. self.dataCubeFFT( )
  872. # canvas.ax1 = canvas.fig.add_axes([.1, .1, .8, .8])
  873. canvas.ax1 = canvas.fig.add_axes([.1, .1, .2, .8])
  874. canvas.ax2 = canvas.fig.add_axes([.325, .1, .2, .8])
  875. canvas.ax3 = canvas.fig.add_axes([.55, .1, .2, .8])
  876. canvas.ax4 = canvas.fig.add_axes([.815, .1, .05, .8]) #cb
  877. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  878. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  879. canvas.ax3.tick_params(axis='both', which='major', labelsize=8)
  880. canvas.ax4.tick_params(axis='both', which='major', labelsize=8)
  881. canvas.ax1.set_ylabel("pulse index", fontsize=8)
  882. canvas.ax1.set_xlabel(r"$\omega$ bin", fontsize=8)
  883. canvas.ax2.set_xlabel(r"$\omega$ bin", fontsize=8)
  884. canvas.ax3.set_xlabel(r"$\omega$ bin", fontsize=8)
  885. canvas.ax2.yaxis.set_ticklabels([])
  886. canvas.ax3.yaxis.set_ticklabels([])
  887. #canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  888. # # Look at pulses
  889. # for pulse in self.DATADICT["PULSES"]:
  890. # for istack in self.DATADICT["stacks"]:
  891. # for ipm in range(0,3):
  892. # canvas.ax1.plot( self.DATADICT[pulse]["CURRENT"][ipm][istack] , label="istack "+str(istack) + " ipm=" + str(ipm) + pulse )
  893. # canvas.draw()
  894. # Create Container for stacks
  895. # sandbox determine pulse sequence again
  896. for pulse in self.DATADICT["PULSES"]:
  897. for ichan in self.DATADICT[pulse]["chan"]:
  898. #for ipm in range(10,11):
  899. CONTAINER = {}
  900. CONTAINER["Cycle 1"] = [] # These are actually subtracted cycles... v+ - v
  901. CONTAINER["Cycle 2"] = []
  902. for istack in self.DATADICT["stacks"]:
  903. #canvas.ax1.clear()
  904. ipm = 8
  905. #for ipm in range(self.DATADICT["nPulseMoments"]):
  906. #canvas.ax1.matshow( np.real(self.DATADICT[pulse][ichan]["FFT"][istack]), aspect='auto' )
  907. #canvas.draw()
  908. if not istack%4%4:
  909. # phase cycle 4, aligned with 1 after sub
  910. CONTAINER["Cycle 1"].append(-self.DATADICT[pulse][ichan]["FFT"][istack])
  911. #canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], -self.DATADICT[pulse][ichan][ipm][istack], label="istack "+str(istack)+ " " + pulse )
  912. elif not istack%4%3:
  913. # phase cycle 3, aligned with 2 after sub
  914. CONTAINER["Cycle 2"].append(-self.DATADICT[pulse][ichan]["FFT"][istack])
  915. #canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], -self.DATADICT[pulse][ichan][ipm][istack], label="istack "+str(istack)+ " " + pulse )
  916. elif not istack%4%2:
  917. # phase cycle 2
  918. CONTAINER["Cycle 2"].append( self.DATADICT[pulse][ichan]["FFT"][istack])
  919. #canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], self.DATADICT[pulse][ichan][ipm][istack], label="istack "+str(istack)+ " " + pulse )
  920. else:
  921. # phase cycle 1
  922. CONTAINER["Cycle 1"].append( self.DATADICT[pulse][ichan]["FFT"][istack])
  923. #canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], self.DATADICT[pulse][ichan][ipm][istack], label="istack "+str(istack)+ " " + pulse )
  924. #canvas.ax1.matshow(np.array(np.average(self.DATADICT[pulse][ichan]["FFT"]), axis=2), aspect='auto' )
  925. #canvas.ax1.plot( self.DATADICT[pulse]["PULSE_TIMES"], self.DATADICT[pulse]["CURRENT"][ipm][istack] , color='black', label="istack "+str(istack) )
  926. #canvas.ax1.plot( self.DATADICT[pulse]["CURRENT"][ipm][istack] , label="istack "+str(istack) + " iFID" + str(iFID) )
  927. #canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], self.DATADICT[pulse][ichan][ipm][istack], label="istack "+str(istack)+ " " + pulse )
  928. #canvas.ax1.legend(prop={'size':6})
  929. #canvas.draw()
  930. # Boostrap
  931. # stack.
  932. #scipy.random.shuffle(x)
  933. # Stack and calculate the pooled variance (http://en.wikipedia.org/wiki/Pooled_variance)
  934. """ All this phase cycling wreaks havoc on a normal calculation of std. and variance. Instead, we resort to calculating
  935. a pooled variance. In this assumption is that the precision of the measurment is constant. This is a poor choice for
  936. any type of moving sensor.
  937. """
  938. # if a window filter has been applied
  939. #self.WINDOW
  940. #self.IWindowStart
  941. #self.iWindowEnd
  942. #self.FFTtimes
  943. CONTAINER = .5*(np.array(CONTAINER["Cycle 2"]) - np.array(CONTAINER["Cycle 1"]))
  944. print ("container shape", np.shape( CONTAINER), self.iWindowStart+1, self.iWindowEnd-1)
  945. dmin = np.min(np.abs(np.average(np.array(CONTAINER)[:,:,self.iWindowStart+1:self.iWindowEnd-1], axis=0)))
  946. dmax = np.max(np.abs(np.average(np.array(CONTAINER)[:,:,self.iWindowStart+1:self.iWindowEnd-1], axis=0)))
  947. mn = canvas.ax1.matshow( 20.*np.log10(np.abs(np.average(np.array(CONTAINER)[:,:, self.iWindowStart+1:self.iWindowEnd-1], axis=0))), aspect='auto', vmin=-120, vmax=-40)
  948. #mn = canvas.ax1.matshow(20.*np.log10(XA[:,istart:iend+1]), aspect='auto', vmax=-40, vmin=-120) #, norm=LogNorm())
  949. canvas.ax2.matshow( 20*np.log10(np.std(np.real(np.array(CONTAINER)[:,:,self.iWindowStart+1:self.iWindowEnd-1]), axis=0)), aspect='auto', vmin=-120, vmax=-40)
  950. canvas.ax3.matshow( 20*np.log10(np.std(np.imag(np.array(CONTAINER)[:,:,self.iWindowStart+1:self.iWindowEnd-1]), axis=0)), aspect='auto', vmin=-120, vmax=-40)
  951. #canvas.ax1.legend(prop={'size':6})
  952. cb1 = mpl.colorbar.Colorbar(canvas.ax4, mn)
  953. cb1.ax.tick_params(labelsize=8)
  954. cb1.set_label("power [dB]", fontsize=8)
  955. canvas.ax1.xaxis.set_major_locator(MaxNLocator(4))
  956. canvas.ax2.xaxis.set_major_locator(MaxNLocator(4))
  957. canvas.ax3.xaxis.set_major_locator(MaxNLocator(4))
  958. canvas.draw()
  959. self.doneTrigger.emit()
  960. def effectivePulseMoment(self, cv, canvas):
  961. canvas.reAxH(2)
  962. nstack = len(self.DATADICT["stacks"])
  963. #canvas.ax1.set_yscale('log')
  964. for pulse in self.DATADICT["PULSES"]:
  965. self.DATADICT[pulse]["qeff"] = {}
  966. self.DATADICT[pulse]["q_nu"] = {}
  967. for ipm in range(self.DATADICT["nPulseMoments"]):
  968. self.DATADICT[pulse]["qeff"][ipm] = {}
  969. self.DATADICT[pulse]["q_nu"][ipm] = {}
  970. #canvas.ax1.clear()
  971. scolours = np.array([0.,0.,1.])
  972. for istack in self.DATADICT["stacks"]:
  973. #self.DATADICT[pulse]["PULSE_TIMES"]
  974. x = self.DATADICT[pulse]["CURRENT"][ipm][istack]
  975. X = np.fft.rfft(x)
  976. v = np.fft.fftfreq(len(x), self.dt)
  977. v = v[0:len(X)]
  978. v[-1] = np.abs(v[-1])
  979. # calculate effective current/moment
  980. I0 = np.abs(X)/len(X)
  981. qeff = I0 * (self.DATADICT[pulse]["PULSE_TIMES"][-1]-self.DATADICT[pulse]["PULSE_TIMES"][0])
  982. canvas.ax1.set_title(r"pulse moment index " +str(ipm), fontsize=10)
  983. canvas.ax1.set_xlabel(r"$\nu$ [Hz]", fontsize=8)
  984. canvas.ax1.set_ylabel(r"$q_{eff}$ [A$\cdot$sec]", fontsize=8)
  985. if nstack > 1:
  986. canvas.ax1.plot(v, qeff, color=scolours+istack*np.array((0.,1./(nstack+1.),-1./(nstack+1.)) )) # eff current
  987. else:
  988. canvas.ax1.plot(v, qeff, color=scolours) # eff current
  989. self.DATADICT[pulse]["qeff"][ipm][istack] = qeff
  990. self.DATADICT[pulse]["q_nu"][ipm][istack] = v
  991. canvas.draw()
  992. percent = int(1e2* (float)((istack)+ipm*self.DATADICT["nPulseMoments"]) /
  993. (float)(len(self.DATADICT["PULSES"])*self.DATADICT["nPulseMoments"]*nstack))
  994. self.progressTrigger.emit(percent)
  995. canvas.draw()
  996. self.plotQeffNu(cv, canvas.ax2)
  997. canvas.draw()
  998. self.doneTrigger.emit()
  999. def plotQeffNu(self, cv, ax):
  1000. ####################################
  1001. # TODO label fid1 and fid2, and make a legend, and colour by pulse
  1002. scolours = ['blue','green']
  1003. nstack = len(self.DATADICT["stacks"])
  1004. iFID = 0
  1005. for pulse in self.DATADICT["PULSES"]:
  1006. self.DATADICT[pulse]["Q"] = np.zeros( (self.DATADICT["nPulseMoments"], len(self.DATADICT["stacks"])) )
  1007. ilabel = True
  1008. for ipm in range(self.DATADICT["nPulseMoments"]):
  1009. scolours = np.array([0.,0.,1.])
  1010. istack = 0
  1011. for stack in self.DATADICT["stacks"]:
  1012. # find index
  1013. icv = int (round(cv / self.DATADICT[pulse]["q_nu"][ipm][stack][1]))
  1014. self.DATADICT[pulse]["Q"][ipm,istack] = self.DATADICT[pulse]["qeff"][ipm][stack][icv]
  1015. if ilabel:
  1016. ax.scatter(ipm, self.DATADICT[pulse]["qeff"][ipm][stack][icv], facecolors='none', edgecolors=scolours, label=(str(pulse)))
  1017. ilabel = False
  1018. else:
  1019. ax.scatter(ipm, self.DATADICT[pulse]["qeff"][ipm][stack][icv], facecolors='none', edgecolors=scolours)
  1020. scolours += np.array((0,1./(nstack+1),-1/(nstack+1.)))
  1021. percent = int(1e2* (float)((istack)+ipm*self.DATADICT["nPulseMoments"]) /
  1022. (float)(len(self.DATADICT["PULSES"])*self.DATADICT["nPulseMoments"]*nstack))
  1023. self.progressTrigger.emit(percent)
  1024. istack += 1
  1025. iFID += 1
  1026. ax.set_xlabel(r"pulse moment index", fontsize=8)
  1027. ax.set_ylabel(r"$q_{eff}$ [A$\cdot$sec]", fontsize=8)
  1028. ax.set_yscale('log')
  1029. ax.set_xlim(0, ax.get_xlim()[1])
  1030. ax.legend(loc='upper right', scatterpoints = 1, prop={'size':6})
  1031. def enableDSP(self):
  1032. self.enableDSPTrigger.emit()
  1033. def adaptiveFilter(self, M, flambda, truncate, mu, PCA, canvas):
  1034. canvas.reAx2(shx=False, shy=False)
  1035. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1036. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1037. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1038. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1039. if truncate:
  1040. itrunc =(int) ( round( 1e-3*truncate*self.samp ) )
  1041. print( "adaptive filter size", 1e3*self.dt*M, " [ms]" )
  1042. Filt = adapt.AdaptiveFilter(flambda)
  1043. H = {}
  1044. for pulse in self.DATADICT["PULSES"]:
  1045. H[pulse] = {}
  1046. for ichan in self.DATADICT[pulse]["chan"]:
  1047. print("setting H", pulse, ichan)
  1048. H[pulse][ichan] = np.zeros(M)
  1049. iFID = 0
  1050. # original ordering...
  1051. #for pulse in self.DATADICT["PULSES"]:
  1052. # for ipm in range(self.DATADICT["nPulseMoments"]):
  1053. # for istack in self.DATADICT["stacks"]:
  1054. # This order makes more sense, same as data collection, verify
  1055. for istack in self.DATADICT["stacks"]:
  1056. for ipm in range(self.DATADICT["nPulseMoments"]):
  1057. for pulse in self.DATADICT["PULSES"]:
  1058. canvas.ax1.clear()
  1059. canvas.ax2.clear()
  1060. for ichan in self.DATADICT[pulse]["chan"]:
  1061. #H = np.zeros(M)
  1062. canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], 1e9* self.DATADICT[pulse][ichan][ipm][istack],\
  1063. label = "noisy")
  1064. RX = []
  1065. for irchan in self.DATADICT[pulse]["rchan"]:
  1066. RX.append(self.DATADICT[pulse][irchan][ipm][istack][::-1])
  1067. if all(H[pulse][ichan]) == 0:
  1068. # call twice to reconcile filter wind-up
  1069. [e,H[pulse][ichan]] = Filt.adapt_filt_Ref( self.DATADICT[pulse][ichan][ipm][istack][::-1],\
  1070. RX,\
  1071. M, mu, PCA, flambda, H[pulse][ichan])
  1072. [e,H[pulse][ichan]] = Filt.adapt_filt_Ref( self.DATADICT[pulse][ichan][ipm][istack][::-1],\
  1073. RX,\
  1074. M, mu, PCA, flambda, H[pulse][ichan])
  1075. else:
  1076. [e,H[pulse][ichan]] = Filt.adapt_filt_Ref( self.DATADICT[pulse][ichan][ipm][istack][::-1],\
  1077. RX,\
  1078. M, mu, PCA, flambda, H[pulse][ichan])
  1079. # replace
  1080. if truncate:
  1081. canvas.ax1.plot( self.DATADICT[pulse]["TIMES"][0:itrunc], 1e9* e[::-1][0:itrunc],\
  1082. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1083. self.DATADICT[pulse][ichan][ipm][istack] = e[::-1][0:itrunc]
  1084. else:
  1085. canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], 1e9* e[::-1],\
  1086. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1087. self.DATADICT[pulse][ichan][ipm][istack] = e[::-1]
  1088. canvas.ax2.plot( H[pulse][ichan] , label="taps")
  1089. canvas.ax1.legend(prop={'size':6})
  1090. canvas.ax2.legend(prop={'size':6})
  1091. canvas.ax1.set_xlabel(r"time [s]", fontsize=8)
  1092. canvas.ax1.set_ylabel(r"signal [nV]", fontsize=8)
  1093. canvas.ax2.set_xlabel(r"filter index", fontsize=8)
  1094. canvas.ax2.set_ylabel(r"scale factor", fontsize=8)
  1095. canvas.draw()
  1096. # truncate the reference channels too, in case you still need them for something.
  1097. # Otherwise they are no longer aligned with the data
  1098. for rchan in self.DATADICT[pulse]["rchan"]:
  1099. if truncate:
  1100. self.DATADICT[pulse][rchan][ipm][istack] = self.DATADICT[pulse][rchan][ipm][istack][0:itrunc]
  1101. #percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/( len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1102. percent = (int)(1e2*((float)(istack*self.DATADICT["nPulseMoments"]+(ipm))/( len(self.DATADICT["PULSES"])*self.nPulseMoments*(len(self.DATADICT["stacks"])+1) )))
  1103. self.progressTrigger.emit(percent)
  1104. # # why is this loop here, istack is not part of rest?
  1105. # for istack in self.DATADICT["stacks"]:
  1106. # if truncate:
  1107. # self.DATADICT[pulse]["TIMES"] = self.DATADICT[pulse]["TIMES"][0:itrunc]
  1108. # percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/( len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1109. # self.progressTrigger.emit(percent)
  1110. # iFID += 1
  1111. if truncate:
  1112. self.DATADICT[pulse]["TIMES"] = self.DATADICT[pulse]["TIMES"][0:itrunc]
  1113. self.doneTrigger.emit()
  1114. self.updateProcTrigger.emit()
  1115. #self.plotFT(canvas)
  1116. def plotFT(self, canvas, istart=0, iend=0):
  1117. try:
  1118. canvas.fig.clear()
  1119. except:
  1120. pass
  1121. canvas.ax1 = canvas.fig.add_axes([.1, .1, .65, .8])
  1122. canvas.ax1c = canvas.fig.add_axes([.8, .1, .05, .8])
  1123. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1124. for pulse in self.DATADICT["PULSES"]:
  1125. for istack in self.DATADICT["stacks"]:
  1126. for ichan in self.DATADICT[pulse]["chan"]:
  1127. # FFT of stack
  1128. XA = np.zeros((self.DATADICT["nPulseMoments"] , len(self.DATADICT[pulse][ichan][0][istack])/2+1))
  1129. nu = np.fft.fftfreq(self.DATADICT[pulse][ichan][0][istack].size, d=self.dt)
  1130. nu[-1] *= -1
  1131. df = nu[1]
  1132. of = 0
  1133. if istart:
  1134. of = nu[istart]
  1135. def freqlabel(x, pos):
  1136. return '%1.0f' %(of + x*df)
  1137. formatter = FuncFormatter(freqlabel)
  1138. canvas.ax1.clear()
  1139. for ipm in range(self.DATADICT["nPulseMoments"]):
  1140. X = np.fft.rfft(self.DATADICT[pulse][ichan][ipm][istack])
  1141. XA[ipm,:] = np.abs(X)
  1142. if istart:
  1143. mn = canvas.ax1.matshow(20.*np.log10(XA[:,istart:iend+1]), aspect='auto', vmax=-40, vmin=-120) #, norm=LogNorm())
  1144. else:
  1145. mn = canvas.ax1.matshow(20.*np.log10(XA), aspect='auto', vmax=-40, vmin=-120) #, norm=LogNorm())
  1146. smin = np.min(20.*np.log10(XA))
  1147. smax = np.max(20.*np.log10(XA))
  1148. canvas.ax1.xaxis.set_major_formatter(formatter)
  1149. cb1 = mpl.colorbar.Colorbar(canvas.ax1c, mn)
  1150. cb1.ax.tick_params(labelsize=8)
  1151. cb1.set_label("signal [dB]", fontsize=8)
  1152. canvas.ax1.set_xlabel(r"$\nu$ [Hz]", fontsize=10)
  1153. canvas.ax1.set_ylabel(r"$q_{index}$", fontsize=10)
  1154. canvas.draw()
  1155. def plotFT(self, canvas, istart=0, iend=0):
  1156. try:
  1157. canvas.fig.clear()
  1158. except:
  1159. pass
  1160. canvas.ax1 = canvas.fig.add_axes([.1, .1, .65, .8])
  1161. canvas.ax1c = canvas.fig.add_axes([.8, .1, .05, .8])
  1162. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1163. for pulse in self.DATADICT["PULSES"]:
  1164. for istack in self.DATADICT["stacks"]:
  1165. for ichan in self.DATADICT[pulse]["chan"]:
  1166. # FFT of stack
  1167. XA = np.zeros((self.DATADICT["nPulseMoments"] , len(self.DATADICT[pulse][ichan][0][istack])//2+1))
  1168. nu = np.fft.fftfreq(self.DATADICT[pulse][ichan][0][istack].size, d=self.dt)
  1169. nu[-1] *= -1
  1170. df = nu[1]
  1171. of = 0
  1172. if istart:
  1173. of = nu[istart]
  1174. def freqlabel(x, pos):
  1175. return '%1.0f' %(of + x*df)
  1176. formatter = FuncFormatter(freqlabel)
  1177. canvas.ax1.clear()
  1178. for ipm in range(self.DATADICT["nPulseMoments"]):
  1179. X = np.fft.rfft(self.DATADICT[pulse][ichan][ipm][istack])
  1180. XA[ipm,:] = np.abs(X)
  1181. if istart:
  1182. mn = canvas.ax1.matshow(20.*np.log10(XA[:,istart:iend+1]), aspect='auto', vmax=-40, vmin=-120, cmap='viridis') #, norm=LogNorm())
  1183. else:
  1184. mn = canvas.ax1.matshow(20.*np.log10(XA), aspect='auto', vmax=-40, vmin=-120, cmap='viridis') #, norm=LogNorm())
  1185. canvas.ax1.xaxis.set_major_formatter(formatter)
  1186. cb1 = mpl.colorbar.Colorbar(canvas.ax1c, mn)
  1187. cb1.ax.tick_params(labelsize=8)
  1188. cb1.set_label("signal [dB]", fontsize=8)
  1189. canvas.ax1.set_xlabel(r"$\nu$ [Hz]", fontsize=10)
  1190. canvas.ax1.set_ylabel(r"$q_{index}$", fontsize=10)
  1191. canvas.draw()
  1192. def dataCubeFFT(self):
  1193. """
  1194. Performs FFT on entire cube of DATA, and REFERENCE channels, but not pulse currents,
  1195. Results are saved to a new field in the data structure
  1196. The GMR varies phase as a function of pulse moment index, so that the first pusle moment is zero phase,
  1197. the second is pi/2 the third is zero. This method corrects for this, so that all pulse moments are in phase.
  1198. Technically we may not want to do this, if there is some system response that this cycles away, and we lose track of
  1199. how many of each cycle we have, could this be problomatic? I think it will come out in the wash as we keep track of the
  1200. rest of the phase cycles. Holy phase cycling batman.
  1201. """
  1202. for pulse in self.DATADICT["PULSES"]:
  1203. for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1204. # FFT of stack
  1205. self.DATADICT[pulse][ichan]["FFT"] = {}
  1206. self.DATADICT[pulse][ichan]["FFT"]["nu"] = np.fft.fftfreq(self.DATADICT[pulse][ichan][0][self.DATADICT["stacks"][0]].size, d=self.dt)
  1207. self.DATADICT[pulse][ichan]["FFT"]["nu"][-1] *= -1
  1208. for istack in self.DATADICT["stacks"]:
  1209. self.DATADICT[pulse][ichan]["FFT"][istack] = np.zeros((self.DATADICT["nPulseMoments"] , len(self.DATADICT[pulse][ichan][0][istack])//2+1), dtype=complex)
  1210. for ipm in range(self.DATADICT["nPulseMoments"]):
  1211. # Mod works for FID pulse sequences, TODO generalize this for 4 phase T1, etc..
  1212. #mod = (-1)**(ipm%2) * (-1)**(istack%2)
  1213. self.DATADICT[pulse][ichan]["FFT"][istack][ipm,:] = np.fft.rfft( self.DATADICT[pulse][ichan][ipm][istack] )
  1214. #if ipm%2:
  1215. # odd, phase cycled from previous
  1216. # self.DATADICT[pulse][ichan]["FFT"][istack][ipm,:] = np.fft.rfft(-self.DATADICT[pulse][ichan][ipm][istack])
  1217. #else:
  1218. # even, we define as zero phase, first pulse moment has this
  1219. # self.DATADICT[pulse][ichan]["FFT"][istack][ipm,:] = np.fft.rfft(self.DATADICT[pulse][ichan][ipm][istack])
  1220. def adaptiveFilterFD(self, ftype, band, centre, canvas):
  1221. try:
  1222. canvas.fig.clear()
  1223. except:
  1224. pass
  1225. canvas.ax1 = canvas.fig.add_axes([.1, .5, .7, .4])
  1226. canvas.ax1c = canvas.fig.add_axes([.85, .5, .05, .4])
  1227. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1228. #canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1229. canvas.ax2 = canvas.fig.add_axes([.1, .05, .7, .4])
  1230. canvas.ax2c = canvas.fig.add_axes([.85, .05, .05, .4])
  1231. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1232. #canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1233. self.dataCubeFFT()
  1234. Filt = adapt.AdaptiveFilter(0.)
  1235. for pulse in self.DATADICT["PULSES"]:
  1236. # Compute window function and dimensions
  1237. [WINDOW, nd, wstart, wend, dead] = self.computeWindow(pulse, band, centre, ftype)
  1238. for istack in self.DATADICT["stacks"]:
  1239. for ichan in self.DATADICT[pulse]["chan"]:
  1240. # FFT of stack
  1241. nd = len(self.DATADICT[pulse][ichan][0][istack])
  1242. XX = np.zeros((self.DATADICT["nPulseMoments"] , len(self.DATADICT[pulse][ichan][0][istack])//2+1), dtype=complex)
  1243. nu = np.fft.fftfreq(self.DATADICT[pulse][ichan][0][istack].size, d=self.dt)
  1244. nu[-1] *= -1
  1245. #nu = self.DATADICT[pulse][ichan]["FFT"]["nu"]
  1246. def freqlabel(x, pos):
  1247. return '%1.0f' %((wstart)*nu[1] + x*nu[1])
  1248. formatter = FuncFormatter(freqlabel)
  1249. canvas.ax1.clear()
  1250. for ipm in range(self.DATADICT["nPulseMoments"]):
  1251. X = np.fft.rfft(self.DATADICT[pulse][ichan][ipm][istack])
  1252. XX[ipm,:] = X
  1253. XX = XX*WINDOW
  1254. XX = XX[:,wstart:wend]
  1255. smin = np.min(20.*np.log10(np.abs(XX)))
  1256. smax = np.max(20.*np.log10(np.abs(XX)))
  1257. #if smin != smin:
  1258. smax = -40
  1259. smin = -120
  1260. mn = canvas.ax1.matshow(20.*np.log10(np.abs(XX)), aspect='auto', vmin=smin, vmax=smax) #, norm=LogNorm())
  1261. canvas.ax1.xaxis.set_major_formatter(formatter)
  1262. cb1 = mpl.colorbar.Colorbar(canvas.ax1c, mn)
  1263. RX = []
  1264. for ichan in self.DATADICT[pulse]["rchan"]:
  1265. R = np.zeros((self.DATADICT["nPulseMoments"] , len(self.DATADICT[pulse][ichan][0][istack])//2+1), dtype=complex)
  1266. for ipm in range(self.DATADICT["nPulseMoments"]):
  1267. R[ipm,:] = np.fft.rfft(self.DATADICT[pulse][ichan][ipm][istack])
  1268. RX.append(R[:,wstart:wend])
  1269. XC = Filt.transferFunctionFFT(XX, RX)
  1270. # TODO inverse FFT, but we need to map back to origional matrix size
  1271. #for ichan in self.DATADICT[pulse]["chan"]:
  1272. # for ipm in range(self.DATADICT["nPulseMoments"]):
  1273. # self.DATADICT[pulse][ichan][ipm][istack] = np.fft.irfft(XC[] , nd)
  1274. mc = canvas.ax2.matshow(20.*np.log10(np.abs(XC)), aspect='auto', vmin=smin, vmax=smax) #, norm=LogNorm())
  1275. cb2 = mpl.colorbar.Colorbar(canvas.ax2c, mc)
  1276. cmin = np.min(20.*np.log10(np.abs(XC)))
  1277. cmax = np.max(20.*np.log10(np.abs(XC)))
  1278. canvas.ax2.xaxis.set_major_formatter(formatter)
  1279. #canvas.ax2.colorbar(mn)
  1280. canvas.draw()
  1281. ##############################3
  1282. # TODO inverse FFT to get the damn data back!!!
  1283. # self.progressTrigger.emit(percent)
  1284. # #label = "iFID="+str(iFID) + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1285. self.doneTrigger.emit()
  1286. def findSpikes(self, x, width, threshold, rollOn):
  1287. import scipy.ndimage as im
  1288. spikes = np.zeros( len(x) )
  1289. med = im.median_filter(x, width,mode='nearest')
  1290. std = np.std(x)
  1291. spikes = (np.abs(x-med) > threshold * std)
  1292. return np.array(np.where(spikes[rollOn::])) + rollOn
  1293. # def despike(self, width, threshold, itype, rollOn, win, canvas):
  1294. # from scipy import interpolate
  1295. # """ This was a stab at a despike filter. Better results were achieved using the SmartStack approach
  1296. # """
  1297. # try:
  1298. # canvas.fig.clear()
  1299. # except:
  1300. # pass
  1301. #
  1302. # canvas.ax1 = canvas.fig.add_axes([.125,.1,.725,.8])
  1303. # canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1304. # canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1305. # iFID = 0
  1306. # for pulse in self.DATADICT["PULSES"]:
  1307. # for ipm in range(self.DATADICT["nPulseMoments"]):
  1308. # for istack in self.DATADICT["stacks"]:
  1309. # canvas.ax1.clear()
  1310. # for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1311. # x = self.findSpikes(self.DATADICT[pulse][ichan][ipm][istack], width, threshold, rollOn)
  1312. # canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], self.DATADICT[pulse][ichan][ipm][istack],
  1313. # label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1314. # canvas.ax1.plot( self.DATADICT[pulse]["TIMES"][x], self.DATADICT[pulse][ichan][ipm][istack][x], '.', color='red' , markersize=6 )
  1315. #
  1316. # FIXED = np.zeros(len(x[0]))
  1317. # ii = 0
  1318. # for spike in np.array(x[0]).tolist():
  1319. # f = interpolate.interp1d(np.delete(self.DATADICT[pulse]["TIMES"][spike-win/2:spike+win/2], x[0]-(spike-win/2)), \
  1320. # np.delete(self.DATADICT[pulse][ichan][ipm][istack][spike-win/2:spike+win/2], x[0]-(spike-win/2)), itype)
  1321. # FIXED[ii] = f(self.DATADICT[pulse]["TIMES"][spike])
  1322. # ii += 1
  1323. # canvas.ax1.plot( self.DATADICT[pulse]["TIMES"][x[0]] , FIXED, '.', color='black' , markersize=4 )
  1324. # self.DATADICT[pulse][ichan][ipm][istack][x[0]] = FIXED
  1325. #
  1326. # canvas.ax1.legend(prop={'size':6})
  1327. # canvas.draw()
  1328. # percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/( len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1329. # self.progressTrigger.emit(percent)
  1330. # iFID += 1
  1331. # self.doneTrigger.emit()
  1332. def designFilter(self, cf, PB, SB, gpass, gstop, ftype, canvas):
  1333. ''' cf is central frequency
  1334. pb is pass band
  1335. sb is stop band
  1336. '''
  1337. TS = (cf) / (.5/self.dt)
  1338. PB = PB / (.5/self.dt) # 1/2 width pass band Muddy Creek
  1339. SB = SB / (.5/self.dt) # 1/2 width stop band Muddy Creek
  1340. # if butterworth
  1341. #[bord, wn] = signal.buttord([TS-PB,TS+PB], [TS-SB,TS+SB], 1e-1, 5.)
  1342. if ftype=="Butterworth":
  1343. [bord, wn] = signal.buttord([TS-PB,TS+PB], [TS-SB,TS+SB], gpass, gstop)
  1344. [self.filt_b, self.filt_a] = signal.butter(bord, wn, btype='bandpass', output='ba')
  1345. [self.filt_z, self.filt_p, self.filt_k] = signal.butter(bord, wn, btype='band', output='zpk')
  1346. elif ftype == "Chebychev Type II":
  1347. [bord, wn] = signal.cheb2ord([TS-PB,TS+PB], [TS-SB,TS+SB], gpass, gstop)
  1348. [self.filt_b, self.filt_a] = signal.cheby2(bord, gstop, wn, btype='bandpass', output='ba')
  1349. [self.filt_z, self.filt_p, self.filt_k] = signal.cheby2(bord, gstop, wn, btype='band', output='zpk')
  1350. elif ftype == "Elliptic":
  1351. [bord, wn] = signal.ellipord([TS-PB,TS+PB], [TS-SB,TS+SB], gpass, gstop)
  1352. [self.filt_b, self.filt_a] = signal.ellip(bord, gpass, gstop, wn, btype='bandpass', output='ba')
  1353. [self.filt_z, self.filt_p, self.filt_k] = signal.ellip(bord, gpass, gstop, wn, btype='band', output='zpk')
  1354. # if cheby2
  1355. impulse = self.mfreqz2(self.filt_b, self.filt_a, canvas)
  1356. self.fe = -5
  1357. for it in range(len(impulse[0])):
  1358. if abs(impulse[1][0][it][0]) >= .1 * gpass:# gpass:
  1359. self.fe = impulse[0][it]
  1360. return [bord, self.fe]
  1361. def downsample(self, truncate, dec, canvas):
  1362. """ Downsamples and truncates the raw signal.
  1363. """
  1364. canvas.reAx2()
  1365. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1366. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1367. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1368. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1369. self.samp /= dec
  1370. self.dt = 1./self.samp
  1371. if truncate:
  1372. itrunc = (int)( 1e-3*truncate*self.samp )
  1373. iFID = 0
  1374. for pulse in self.DATADICT["PULSES"]:
  1375. for ipm in range(self.DATADICT["nPulseMoments"]):
  1376. for istack in self.DATADICT["stacks"]:
  1377. canvas.ax1.clear()
  1378. canvas.ax2.clear()
  1379. for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1380. # trim off indices that don't divide evenly
  1381. ndi = np.shape(self.DATADICT[pulse][ichan][ipm][istack])[0]%dec
  1382. if ndi:
  1383. [self.DATADICT[pulse][ichan][ipm][istack], RSTIMES] = signal.resample(self.DATADICT[pulse][ichan][ipm][istack][0:-ndi],\
  1384. len(self.DATADICT[pulse][ichan][ipm][istack][0:-ndi])//dec,\
  1385. self.DATADICT[pulse]["TIMES"][0:-ndi], window='hamm')
  1386. else:
  1387. [self.DATADICT[pulse][ichan][ipm][istack], RSTIMES] = signal.resample(self.DATADICT[pulse][ichan][ipm][istack],\
  1388. len(self.DATADICT[pulse][ichan][ipm][istack])//dec,\
  1389. self.DATADICT[pulse]["TIMES"], window='hamm')
  1390. if truncate:
  1391. self.DATADICT[pulse][ichan][ipm][istack] = self.DATADICT[pulse][ichan][ipm][istack][0:itrunc]
  1392. RSTIMES = RSTIMES[0:itrunc]
  1393. for ichan in self.DATADICT[pulse]["chan"]:
  1394. canvas.ax2.plot( RSTIMES, 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1395. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1396. for ichan in self.DATADICT[pulse]["rchan"]:
  1397. canvas.ax1.plot( RSTIMES, 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1398. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1399. canvas.ax1.set_xlabel(r"time [s]", fontsize=8)
  1400. canvas.ax1.set_ylabel(r"signal [nV]", fontsize=8)
  1401. canvas.ax2.set_xlabel(r"time [s]", fontsize=8)
  1402. canvas.ax2.set_ylabel(r"signal [nV]", fontsize=8)
  1403. canvas.ax1.legend(prop={'size':6})
  1404. canvas.ax2.legend(prop={'size':6})
  1405. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1406. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1407. canvas.draw()
  1408. percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/( len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1409. self.progressTrigger.emit(percent)
  1410. iFID += 1
  1411. self.DATADICT[pulse]["TIMES"] = RSTIMES
  1412. #####################################
  1413. # resample pulse data
  1414. for pulse in self.DATADICT["PULSES"]:
  1415. for ipm in range(self.DATADICT["nPulseMoments"]):
  1416. for istack in self.DATADICT["stacks"]:
  1417. ndi = np.shape(self.DATADICT[pulse]["CURRENT"][ipm][istack])[0]%dec
  1418. if ndi:
  1419. [self.DATADICT[pulse]["CURRENT"][ipm][istack], RSPTIMES] = signal.resample(self.DATADICT[pulse]["CURRENT"][ipm][istack][0:-ndi],\
  1420. len(self.DATADICT[pulse]["CURRENT"][ipm][istack][0:-ndi])//dec,\
  1421. self.DATADICT[pulse]["PULSE_TIMES"][0:-ndi], window='hamm')
  1422. else:
  1423. [self.DATADICT[pulse]["CURRENT"][ipm][istack], RSPTIMES] = signal.resample(self.DATADICT[pulse]["CURRENT"][ipm][istack],\
  1424. len(self.DATADICT[pulse]["CURRENT"][ipm][istack])//dec,\
  1425. self.DATADICT[pulse]["PULSE_TIMES"], window='hamm')
  1426. self.DATADICT[pulse]["PULSE_TIMES"] = RSPTIMES
  1427. self.doneTrigger.emit()
  1428. self.updateProcTrigger.emit()
  1429. def computeWindow(self, pulse, band, centre, ftype, canvas=None):
  1430. # Compute window
  1431. nd = len(self.DATADICT[pulse][self.DATADICT[pulse]["chan"][0]][0][self.DATADICT["stacks"][0]])
  1432. fft1 = np.fft.rfft(self.DATADICT[pulse][self.DATADICT[pulse]["chan"][0]][0][self.DATADICT["stacks"][0]])
  1433. freqs = np.fft.fftfreq(nd, self.dt)
  1434. df = freqs[1] - freqs[0]
  1435. N = int((round)(band/df))
  1436. if ftype == "Hamming":
  1437. window = np.hamming(N)
  1438. elif ftype == "Hanning":
  1439. window = np.hanning(N)
  1440. elif ftype == "Rectangular":
  1441. window = np.ones(N)
  1442. elif ftype == "Flat top":
  1443. window = signal.flattop(N)
  1444. else:
  1445. print ("in windowFilter, window type undefined")
  1446. WINDOW = np.zeros(len(fft1))
  1447. ifreq = int(round(centre/df))
  1448. istart = ifreq-len(window)//2
  1449. iend = 0
  1450. if N%2:
  1451. WINDOW[ifreq-N//2:ifreq+N//2+1] = window
  1452. iend = ifreq+N//2+1
  1453. else:
  1454. WINDOW[ifreq-N//2:ifreq+N//2] = window
  1455. iend = ifreq+N//2
  1456. self.WINDOW = WINDOW
  1457. self.iWindowStart = istart
  1458. self.iWindowEnd = iend
  1459. self.FFTtimes = nd
  1460. fft1 = np.fft.irfft(WINDOW)
  1461. # calculate dead time
  1462. self.windead = 0.
  1463. for ift in np.arange(100,0,-1):
  1464. #print( ift, fft1[ift] )
  1465. if fft1[ift] > .001:
  1466. #print ("DEAD TIME", 1e3*self.DATADICT[pulse]["TIMES"][ift] - 1e3*self.DATADICT[pulse]["TIMES"][0] )
  1467. dead = 1e3*self.DATADICT[pulse]["TIMES"][ift] - 1e3*self.DATADICT[pulse]["TIMES"][0]
  1468. self.windead = self.DATADICT[pulse]["TIMES"][ift] - self.DATADICT[pulse]["TIMES"][0]
  1469. break
  1470. if canvas != None:
  1471. canvas.fig.clear()
  1472. canvas.ax1 = canvas.fig.add_axes([.1, .6, .75, .35])
  1473. canvas.ax2 = canvas.fig.add_axes([.1, .1, .75, .35])
  1474. canvas.ax1.plot(WINDOW)
  1475. canvas.ax2.plot( 1e3* self.DATADICT[pulse]["TIMES"][0:100] - 1e3*self.DATADICT[pulse]["TIMES"][0], fft1[0:100] )
  1476. canvas.ax2.set_xlabel("time (ms)")
  1477. canvas.ax2.set_title("IFFT")
  1478. canvas.draw()
  1479. return [WINDOW, nd, istart, iend, dead]
  1480. def windowFilter(self, ftype, band, centre, canvas):
  1481. ###############################
  1482. # Window Filter (Ormsby filter http://www.xsgeo.com/course/filt.htm)
  1483. # apply window
  1484. iFID = 0
  1485. for pulse in self.DATADICT["PULSES"]:
  1486. [WINDOW, nd, istart, iend,dead] = self.computeWindow(pulse, band, centre, ftype)
  1487. for istack in self.DATADICT["stacks"]:
  1488. for ipm in range(self.DATADICT["nPulseMoments"]):
  1489. for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1490. fft = np.fft.rfft( self.DATADICT[pulse][ichan][ipm][istack] )
  1491. fft *= WINDOW
  1492. self.DATADICT[pulse][ichan][ipm][istack] = np.fft.irfft(fft , nd)
  1493. percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/(len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1494. self.progressTrigger.emit(percent)
  1495. iFID += 1
  1496. self.plotFT(canvas, istart, iend)
  1497. self.doneTrigger.emit()
  1498. def bandpassFilter(self, canvas, blank, plot=True):
  1499. if plot:
  1500. canvas.reAx2()
  1501. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1502. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1503. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1504. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1505. ife = (int)( max(self.fe, self.windead) * self.samp )
  1506. # Data
  1507. iFID = 0
  1508. for pulse in self.DATADICT["PULSES"]:
  1509. self.DATADICT[pulse]["TIMES"] = self.DATADICT[pulse]["TIMES"][ife:-ife]
  1510. for ipm in range(self.DATADICT["nPulseMoments"]):
  1511. for istack in self.DATADICT["stacks"]:
  1512. canvas.ax1.clear()
  1513. canvas.ax2.clear()
  1514. #for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1515. for ichan in self.DATADICT[pulse]["rchan"]:
  1516. # reflect signal back on itself to reduce gibbs effects on early times
  1517. #nr = len( self.DATADICT[pulse][ichan][ipm][istack] ) - 1 + ife
  1518. #refl = np.append( -1*self.DATADICT[pulse][ichan][ipm][istack][::-1][0:-1], self.DATADICT[pulse][ichan][ipm][istack] )
  1519. #reflfilt = signal.filtfilt( self.filt_b, self.filt_a, refl )
  1520. #self.DATADICT[pulse][ichan][ipm][istack] = reflfilt[nr:-ife]
  1521. # don't reflect
  1522. self.DATADICT[pulse][ichan][ipm][istack] = \
  1523. signal.filtfilt(self.filt_b, self.filt_a, self.DATADICT[pulse][ichan][ipm][istack])[ife:-ife]
  1524. # plot
  1525. if plot:
  1526. canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1527. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " rchan=" + str(ichan))
  1528. for ichan in self.DATADICT[pulse]["chan"]:
  1529. # reflect signal back on itself to reduce gibbs effects on early times
  1530. #nr = len( self.DATADICT[pulse][ichan][ipm][istack] ) - 1 + ife
  1531. #refl = np.append( -1*self.DATADICT[pulse][ichan][ipm][istack][::-1][0:-1], self.DATADICT[pulse][ichan][ipm][istack] )
  1532. #reflfilt = signal.filtfilt( self.filt_b, self.filt_a, refl )
  1533. #self.DATADICT[pulse][ichan][ipm][istack] = reflfilt[nr:-ife]
  1534. # don't reflect
  1535. self.DATADICT[pulse][ichan][ipm][istack] = \
  1536. scipy.signal.filtfilt(self.filt_b, self.filt_a, self.DATADICT[pulse][ichan][ipm][istack])[ife:-ife]
  1537. # plot
  1538. if plot:
  1539. canvas.ax2.plot( self.DATADICT[pulse]["TIMES"], 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1540. label = "data " + pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " chan=" + str(ichan))
  1541. if plot:
  1542. canvas.ax1.set_xlabel(r"time [s]", fontsize=8)
  1543. canvas.ax1.set_ylabel(r"signal [nV]", fontsize=8)
  1544. canvas.ax2.set_xlabel(r"time [s]", fontsize=8)
  1545. canvas.ax2.set_ylabel(r"signal [nV]", fontsize=8)
  1546. canvas.ax1.legend(prop={'size':6})
  1547. canvas.ax2.legend(prop={'size':6})
  1548. canvas.draw()
  1549. percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/(len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1550. self.progressTrigger.emit(percent)
  1551. iFID += 1
  1552. self.doneTrigger.emit()
  1553. self.updateProcTrigger.emit()
  1554. def loadGMRBinaryFID( self, rawfname, istack ):
  1555. """ Reads a single binary GMR file and fills into DATADICT
  1556. """
  1557. #################################################################################
  1558. # figure out key data indices
  1559. # Pulse
  1560. nps = (int)((self.prePulseDelay)*self.samp)
  1561. npul = (int)(self.pulseLength[0]*self.samp) #+ 100
  1562. # Data
  1563. nds = nps+npul+(int)((self.deadTime)*self.samp); # indice pulse 1 data starts
  1564. nd1 = (int)(1.*self.samp) # samples in first pulse
  1565. invGain = 1./self.RxGain
  1566. invCGain = self.CurrentGain
  1567. pulse = "Pulse 1"
  1568. chan = self.DATADICT[pulse]["chan"]
  1569. rchan = self.DATADICT[pulse]["rchan"]
  1570. rawFile = open( rawfname, 'rb')
  1571. for ipm in range(self.nPulseMoments):
  1572. buf1 = rawFile.read(4)
  1573. buf2 = rawFile.read(4)
  1574. N_chan = struct.unpack('>i', buf1 )[0]
  1575. N_samp = struct.unpack('>i', buf2 )[0]
  1576. T = N_samp * self.dt
  1577. TIMES = np.arange(0, T, self.dt) - .0002 # small offset in GMR DAQ?
  1578. DATA = np.zeros([N_samp, N_chan+1])
  1579. for ichan in range(N_chan):
  1580. DATADUMP = rawFile.read(4*N_samp)
  1581. for irec in range(N_samp):
  1582. DATA[irec,ichan] = struct.unpack('>f', DATADUMP[irec*4:irec*4+4])[0]
  1583. # Save into Data Cube
  1584. for ichan in chan:
  1585. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,eval(ichan)+3][nds:nds+nd1] * invGain
  1586. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1587. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,1][nps:nps+npul] * invCGain
  1588. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  1589. # reference channels?
  1590. for ichan in rchan:
  1591. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,eval(ichan)+3][nds:nds+nd1] * invGain
  1592. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1593. def loadGMRASCIIFID( self, rawfname, istack ):
  1594. """Based on the geoMRI instrument manufactured by VistaClara. Imports
  1595. a suite of raw .lvm files with the following format (on one line)
  1596. time(s) DC_Bus/100(V) Current+/75(A) Curr-/75(A) Voltage+/200(V) \
  1597. Ch1(V) Ch2(V) Ch3(V) Ch4(V)
  1598. Sampling rate is assumed at 50 kHz
  1599. """
  1600. import pandas as pd
  1601. #################################################################################
  1602. # figure out key data indices
  1603. # Pulse
  1604. nps = (int)((self.prePulseDelay)*self.samp)
  1605. npul = (int)(self.pulseLength[0]*self.samp) #+ 100
  1606. # Data
  1607. nds = nps+npul+(int)((self.deadTime)*self.samp); # indice pulse 1 data starts
  1608. nd1 = (int)(1.*self.samp) - nds # samples in first pulse
  1609. ndr = (int)(1.*self.samp) # samples in record
  1610. invGain = 1./self.RxGain
  1611. invCGain = self.CurrentGain
  1612. pulse = "Pulse 1"
  1613. chan = self.DATADICT[pulse]["chan"]
  1614. rchan = self.DATADICT[pulse]["rchan"]
  1615. T = 1.5 #N_samp * self.dt
  1616. TIMES = np.arange(0, T, self.dt) - .0002 # small offset in GMR DAQ?
  1617. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1618. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  1619. # pandas is much faster than numpy for io
  1620. #DATA = np.loadtxt(rawfname)
  1621. DATA = pd.read_csv(rawfname, header=None, sep="\t").values
  1622. for ipm in range(self.nPulseMoments):
  1623. for ichan in np.append(chan,rchan):
  1624. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:, eval(ichan)+4][nds:(nds+nd1)] * invGain
  1625. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,2][nps:nps+npul] * invCGain
  1626. nds += ndr
  1627. nps += ndr
  1628. def loadFIDData(self, base, procStacks, chanin, rchanin, FIDProc, canvas, deadTime, plot):
  1629. '''
  1630. Loads a GMR FID dataset, reads binary and ASCII format files
  1631. '''
  1632. canvas.reAx3(True,False)
  1633. chan = []
  1634. for ch in chanin:
  1635. chan.append(str(ch))
  1636. rchan = []
  1637. for ch in rchanin:
  1638. rchan.append(str(ch))
  1639. # not in any headers but this has changed, NOT the place to do this. MOVE
  1640. #self.prePulseDelay = 0.01 # delay before pulse
  1641. self.deadTime = deadTime # instrument dead time before measurement
  1642. self.samp = 50000. # in case this is a reproc, these might have
  1643. self.dt = 1./self.samp # changed
  1644. #################################################################################
  1645. # Data structures
  1646. PULSES = [FIDProc]
  1647. PULSES = ["Pulse 1"]
  1648. self.DATADICT = {}
  1649. self.DATADICT["nPulseMoments"] = self.nPulseMoments
  1650. self.DATADICT["stacks"] = procStacks
  1651. self.DATADICT["PULSES"] = PULSES
  1652. for pulse in PULSES:
  1653. self.DATADICT[pulse] = {}
  1654. self.DATADICT[pulse]["chan"] = chan # TODO these should not be a subet of pulse! for GMR all
  1655. self.DATADICT[pulse]["rchan"] = rchan # data are consistent
  1656. self.DATADICT[pulse]["CURRENT"] = {}
  1657. for ichan in np.append(chan,rchan):
  1658. self.DATADICT[pulse][ichan] = {}
  1659. for ipm in range(self.nPulseMoments):
  1660. self.DATADICT[pulse][ichan][ipm] = {}
  1661. self.DATADICT[pulse]["CURRENT"][ipm] = {}
  1662. for istack in procStacks:
  1663. self.DATADICT[pulse][ichan][ipm][istack] = np.zeros(3)
  1664. self.DATADICT[pulse]["CURRENT"][ipm][istack] = np.zeros(3)
  1665. ##############################################
  1666. # Read in binary (.lvm) data
  1667. iistack = 0
  1668. fnames = []
  1669. for istack in procStacks:
  1670. if self.nDAQVersion < 2.3:
  1671. #rawfname = base + "_" + str(istack)
  1672. self.loadGMRASCIIFID( base + "_" + str(istack), istack )
  1673. else:
  1674. self.loadGMRBinaryFID( base + "_" + str(istack) + ".lvm", istack )
  1675. #fnames.append( base + "_" + str(istack) + ".lvm" )
  1676. percent = (int) (1e2*((float)((iistack*self.nPulseMoments+ipm+1)) / (len(procStacks)*self.nPulseMoments)))
  1677. self.progressTrigger.emit(percent)
  1678. iistack += 1
  1679. # multiprocessing load data
  1680. #info = {}
  1681. #info["prePulseDelay"] = self.prePulseDelay
  1682. #with multiprocessing.Pool() as pool:
  1683. # results = pool.starmap( loadGMRBinaryFID, zip(itertools.repeat(self), fnames, info ) ) # zip(np.tile(vc, (ns, 1)), np.tile(vgc, (ns,1)), itertools.repeat(sys.argv[1]), itertools.repeat(sys.argv[2]), EPS_CMR))
  1684. # Plotting
  1685. if plot:
  1686. iistack = 0
  1687. for istack in procStacks:
  1688. for ipm in range(self.nPulseMoments):
  1689. canvas.ax1.clear()
  1690. canvas.ax2.clear()
  1691. canvas.ax3.clear()
  1692. for ichan in chan:
  1693. canvas.ax1.plot(self.DATADICT["Pulse 1"]["PULSE_TIMES"], self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] , color='black')
  1694. canvas.ax3.plot(self.DATADICT["Pulse 1"]["TIMES"], self.DATADICT["Pulse 1"][ichan][ipm][istack], label="Pulse 1 FID data ch. "+str(ichan)) #, color='blue')
  1695. for ichan in rchan:
  1696. canvas.ax2.plot(self.DATADICT["Pulse 1"]["TIMES"], self.DATADICT["Pulse 1"][ichan][ipm][istack], label="Pulse 1 FID ref ch. "+str(ichan)) #, color='blue')
  1697. canvas.ax3.legend(prop={'size':6})
  1698. canvas.ax2.legend(prop={'size':6})
  1699. canvas.ax1.set_title("stack "+str(istack)+" pulse index " + str(ipm), fontsize=8)
  1700. canvas.ax1.set_xlabel("time [s]", fontsize=8)
  1701. canvas.ax1.set_ylabel("Current [A]", fontsize=8)
  1702. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1703. canvas.ax2.set_ylabel("RAW signal [V]", fontsize=8)
  1704. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1705. canvas.ax2.tick_params(axis='both', which='minor', labelsize=6)
  1706. canvas.ax2.set_xlabel("time [s]", fontsize=8)
  1707. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1708. canvas.ax3.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1709. canvas.draw()
  1710. percent = (int) (1e2*((float)((iistack*self.nPulseMoments+ipm+1)) / (len(procStacks)*self.nPulseMoments)))
  1711. self.progressTrigger.emit(percent)
  1712. iistack += 1
  1713. self.enableDSP()
  1714. self.doneTrigger.emit()
  1715. def load4PhaseT1Data(self, base, procStacks, chan, rchan, FIDProc, canvas, deadTime, plot):
  1716. """
  1717. Designed to load GMR 4-phase data which use the following convention for phase cycles
  1718. P1 P2
  1719. Stack 1 -> 0 0 <-- <--
  1720. Stack 2 -> 0 pi/2 | <-- <--
  1721. Stack 3 -> pi/2 0 <-- | <--
  1722. Stack 4 -> pi/2 pi/2 <-- <--
  1723. The cycle is determined by stack indice. Walbrecker proposes for pulse2 data (Stack2 - Stack1) / 2
  1724. equivalently (Stack 4 - Stack3) will yield the same voltage response wrt. the second pulse.
  1725. Alternatively Stack 4 can be converted to be aligned with Stack 1 by negating, and Stack 3 Can be aligned with Stack 2 by negating
  1726. Then there are just the two phase cycles that can be stacked like normal.
  1727. Unfortunately, we need to stack each cycle first, then perform corrections for phase cycling. The reason for this is that otherwise,
  1728. the entire point is lost, as the signal that is desired to be cancelled out may not be balanced evenly across the stacks. That is to say,
  1729. if there is an uneven number of a certain phase cycle.
  1730. We could, I suppose impose this condition, but I think I would rather not?
  1731. + more samples for std. deviation calculation
  1732. + single spikes will have less residual effect
  1733. - can no longer do normality tests etc. and remove data that are suspect.
  1734. - requires a dumb stack, and may also require removal of entire stacks of data
  1735. Additonally, the GMR varies phase as a function of pulse moment index, so that the first pusle moment is zero phase, the second is pi/2 the third is zero ...
  1736. This however, is altered by the above convention. It gets a little complicated...
  1737. """
  1738. import struct
  1739. canvas.reAx2()
  1740. # not in any headers but this has changed, NOT the place to do this. MOVE
  1741. self.prePulseDelay = 0.01 # delay before pulse
  1742. self.deadTime = deadTime # instrument dead time before measurement
  1743. self.samp = 50000. # in case this is a reproc, these might have
  1744. self.dt = 1./self.samp # changed
  1745. invGain = 1./self.RxGain
  1746. invCGain = self.CurrentGain
  1747. #################################################################################
  1748. # figure out key data indices
  1749. # Pulse
  1750. nps = (int)((self.prePulseDelay)*self.samp)
  1751. nps2 = (int)((self.prePulseDelay+self.interpulseDelay)*self.samp)
  1752. npul = (int)(self.pulseLength[0]*self.samp) #+ 100
  1753. np2 = (int)(self.pulseLength[1]*self.samp) #+ 100
  1754. # Data
  1755. nds = nps+npul+(int)((self.deadTime)*self.samp); # indice pulse 1 data starts
  1756. nd1 = (int)((self.interpulseDelay)*self.samp) # samples in first pulse
  1757. nd2s = nps+npul+nd1+(int)((self.deadTime)*self.samp); # indice pulse 2 data starts
  1758. nd2 = (int)((1.)*self.samp) # samples in first pulse
  1759. nd1 -= (int)((.028)*self.samp) + nps # some time to get ready for next pulse
  1760. #################################################################################
  1761. # Data structures
  1762. PULSES = [FIDProc]
  1763. if FIDProc == "Both":
  1764. PULSES = ["Pulse 1","Pulse 2"]
  1765. self.DATADICT = {}
  1766. self.DATADICT["nPulseMoments"] = self.nPulseMoments
  1767. self.DATADICT["stacks"] = procStacks
  1768. self.DATADICT["PULSES"] = PULSES
  1769. for pulse in PULSES:
  1770. self.DATADICT[pulse] = {}
  1771. self.DATADICT[pulse]["chan"] = chan
  1772. self.DATADICT[pulse]["rchan"] = rchan
  1773. self.DATADICT[pulse]["CURRENT"] = {}
  1774. for ichan in np.append(chan,rchan):
  1775. self.DATADICT[pulse][ichan] = {}
  1776. for ipm in range(self.nPulseMoments):
  1777. self.DATADICT[pulse][ichan][ipm] = {}
  1778. self.DATADICT[pulse]["CURRENT"][ipm] = {}
  1779. for istack in procStacks:
  1780. self.DATADICT[pulse][ichan][ipm][istack] = np.zeros(3)
  1781. self.DATADICT[pulse]["CURRENT"][ipm][istack] = np.zeros(3)
  1782. ##############################################
  1783. # Read in binary data
  1784. iistack = 0
  1785. for istack in procStacks:
  1786. rawFile = open(base + "_" + str(istack) + ".lvm", 'rb')
  1787. for ipm in range(self.nPulseMoments):
  1788. N_chan = struct.unpack('>i', rawFile.read(4))[0]
  1789. N_samp = struct.unpack('>i', rawFile.read(4))[0]
  1790. T = N_samp * self.dt
  1791. TIMES = np.arange(0, T, self.dt) - .0002 # small offset in GMR DAQ?
  1792. DATA = np.zeros([N_samp, N_chan+1])
  1793. for ichan in range(N_chan):
  1794. DATADUMP = rawFile.read(4*N_samp)
  1795. for irec in range(N_samp):
  1796. DATA[irec,ichan] = struct.unpack('>f', DATADUMP[irec*4:irec*4+4])[0]
  1797. if plot:
  1798. canvas.ax1.clear()
  1799. canvas.ax2.clear()
  1800. li = np.shape( DATA[:,4][nd2s:nd2s+nd2] )[0]
  1801. ######################################
  1802. # save into DATA cube
  1803. # TODO, changing iFID to 'Pulse 1' or 'Pulse 2'
  1804. for ichan in chan:
  1805. if FIDProc == "Pulse 1":
  1806. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  1807. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1808. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,1][nps:nps+npul] * invCGain
  1809. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  1810. if plot:
  1811. canvas.ax1.plot(self.DATADICT["Pulse 1"]["TIMES"], self.DATADICT["Pulse 1"][ichan][ipm][istack], label="Pulse 1 FID data ch. "+str(ichan)) #, color='blue')
  1812. canvas.ax2.plot(self.DATADICT["Pulse 1"]["PULSE_TIMES"], self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] , color='black')
  1813. elif FIDProc == "Pulse 2":
  1814. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] *invGain
  1815. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  1816. self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack] = DATA[:,1][nps2:nps2+np2] * invCGain
  1817. self.DATADICT["Pulse 2"]["PULSE_TIMES"] = TIMES[nps2:nps2+np2]
  1818. if plot:
  1819. canvas.ax1.plot(self.DATADICT["Pulse 2"]["TIMES"], self.DATADICT["Pulse 2"][ichan][ipm][istack], label="Pulse 2 FID data ch. "+str(ichan)) #, color='blue')
  1820. canvas.ax2.plot( self.DATADICT["Pulse 2"]["PULSE_TIMES"], self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack], color='black' )
  1821. else:
  1822. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  1823. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] * invGain
  1824. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1825. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  1826. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,1][nps:nps+npul] * invCGain
  1827. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  1828. self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack] = DATA[:,1][nps2:nps2+np2] * invCGain
  1829. self.DATADICT["Pulse 2"]["PULSE_TIMES"] = TIMES[nps2:nps2+np2]
  1830. if plot:
  1831. canvas.ax1.plot(self.DATADICT["Pulse 1"]["TIMES"], self.DATADICT["Pulse 1"][ichan][ipm][istack], label="Pulse 1 FID data ch. "+str(ichan)) #, color='blue')
  1832. canvas.ax1.plot(self.DATADICT["Pulse 2"]["TIMES"], self.DATADICT["Pulse 2"][ichan][ipm][istack], label="Pulse 2 FID data ch. "+str(ichan)) #, color='blue')
  1833. canvas.ax2.plot( self.DATADICT["Pulse 1"]["PULSE_TIMES"], self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] , color='black' )
  1834. canvas.ax2.plot( self.DATADICT["Pulse 2"]["PULSE_TIMES"], self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack] , color='black')
  1835. for ichan in rchan:
  1836. if FIDProc == "Pulse 1":
  1837. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  1838. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1839. if plot:
  1840. canvas.ax1.plot(self.DATADICT["Pulse 1"]["TIMES"], self.DATADICT["Pulse 1"][ichan][ipm][istack], label="Pulse 1 FID ref ch. "+str(ichan)) #, color='blue')
  1841. elif FIDProc == "Pulse 2":
  1842. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] * invGain
  1843. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  1844. if plot:
  1845. canvas.ax1.plot(self.DATADICT["Pulse 2"]["TIMES"], self.DATADICT["Pulse 2"][ichan][ipm][istack], label="Pulse 2 FID ref ch. "+str(ichan)) #, color='blue')
  1846. else:
  1847. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  1848. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] * invGain
  1849. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1850. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  1851. if plot:
  1852. canvas.ax1.plot(self.DATADICT["Pulse 1"]["TIMES"], self.DATADICT["Pulse 1"][ichan][ipm][istack], label="Pulse 1 FID ref ch. "+str(ichan)) #, color='blue')
  1853. canvas.ax1.plot(self.DATADICT["Pulse 2"]["TIMES"], self.DATADICT["Pulse 2"][ichan][ipm][istack], label="Pulse 2 FID ref ch. "+str(ichan)) #, color='blue')
  1854. if plot:
  1855. canvas.ax1.legend(prop={'size':6})
  1856. canvas.ax1.set_title("stack "+str(istack)+" pulse index " + str(ipm), fontsize=8)
  1857. canvas.ax1.set_xlabel("time [s]", fontsize=8)
  1858. canvas.ax1.set_ylabel("RAW signal [V]", fontsize=8)
  1859. canvas.ax2.set_ylabel("Current [A]", fontsize=8)
  1860. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1861. canvas.ax2.tick_params(axis='both', which='minor', labelsize=6)
  1862. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1863. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1864. canvas.draw()
  1865. # update GUI of where we are
  1866. percent = (int) (1e2*((float)((iistack*self.nPulseMoments+ipm+1)) / (len(procStacks)*self.nPulseMoments)))
  1867. self.progressTrigger.emit(percent)
  1868. iistack += 1
  1869. self.enableDSP()
  1870. self.doneTrigger.emit()
  1871. if __name__ == "__main__":
  1872. if len(sys.argv) < 4:
  1873. print( "mrsurvey path/to/header <stack1> <stackN> ")
  1874. exit()
  1875. GMR = GMRDataProcessor()
  1876. GMR.readHeaderFile(sys.argv[1])
  1877. GMR.Print()
  1878. if GMR.pulseType == "FID":
  1879. GMR.loadFIDData(sys.argv[1], sys.argv[2], sys.argv[3], 5)
  1880. if GMR.pulseType == "4PhaseT1":
  1881. GMR.load4PhaseT1Data(sys.argv[1], sys.argv[2], sys.argv[3], 5)
  1882. pylab.show()