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

mrsurvey.py 133KB

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