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

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