Surface NMR processing and inversion GUI
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

mrsurvey.py 155KB

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