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

mrsurvey.py 144KB

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