Surface NMR processing and inversion GUI
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

mrsurvey.py 143KB

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