Surface NMR processing and inversion GUI
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

mrsurvey.py 147KB

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