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

mrsurvey.py 145KB

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