Surface NMR processing and inversion GUI
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

mrsurvey.py 130KB

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