Surface NMR processing and inversion GUI
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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