Surface NMR processing and inversion GUI
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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