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

mrsurvey.py 130KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523
  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, f0, 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, 40, self.DATADICT[pulse]["TIMES"] )
  466. #self.DATADICT[pulse][ichan][ipm][istack] = harmonic.minHarmonic2( f0-.25, f0+.25, self.DATADICT[pulse][ichan][ipm][istack], self.samp, 20, 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, 40, self.DATADICT[pulse]["TIMES"] )
  476. #self.DATADICT[pulse][ichan][ipm][istack] = harmonic.minHarmonic2( f0-.25, f0+.25, self.DATADICT[pulse][ichan][ipm][istack], self.samp, 20, self.DATADICT[pulse]["TIMES"] )
  477. #self.DATADICT[pulse][ichan][ipm][istack] = harmonic.harmonic( f0, self.DATADICT[pulse][ichan][ipm][istack], self.samp, 50, 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. return [bord, self.fe]
  1639. def downsample(self, truncate, dec, canvas):
  1640. """ Downsamples and truncates the raw signal.
  1641. """
  1642. canvas.reAx2()
  1643. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1644. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1645. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1646. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1647. self.samp /= dec
  1648. self.dt = 1./self.samp
  1649. if truncate:
  1650. itrunc = (int)( 1e-3*truncate*self.samp )
  1651. iFID = 0
  1652. for pulse in self.DATADICT["PULSES"]:
  1653. for ipm in range(self.DATADICT["nPulseMoments"]):
  1654. for istack in self.DATADICT["stacks"]:
  1655. canvas.ax1.clear()
  1656. canvas.ax2.clear()
  1657. for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1658. # trim off indices that don't divide evenly
  1659. ndi = np.shape(self.DATADICT[pulse][ichan][ipm][istack])[0]%dec
  1660. if ndi:
  1661. [self.DATADICT[pulse][ichan][ipm][istack], RSTIMES] = signal.resample(self.DATADICT[pulse][ichan][ipm][istack][0:-ndi],\
  1662. len(self.DATADICT[pulse][ichan][ipm][istack][0:-ndi])//dec,\
  1663. self.DATADICT[pulse]["TIMES"][0:-ndi], window='hamm')
  1664. else:
  1665. [self.DATADICT[pulse][ichan][ipm][istack], RSTIMES] = signal.resample(self.DATADICT[pulse][ichan][ipm][istack],\
  1666. len(self.DATADICT[pulse][ichan][ipm][istack])//dec,\
  1667. self.DATADICT[pulse]["TIMES"], window='hamm')
  1668. if truncate:
  1669. self.DATADICT[pulse][ichan][ipm][istack] = self.DATADICT[pulse][ichan][ipm][istack][0:itrunc]
  1670. RSTIMES = RSTIMES[0:itrunc]
  1671. for ichan in self.DATADICT[pulse]["chan"]:
  1672. canvas.ax2.plot( RSTIMES, 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1673. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1674. for ichan in self.DATADICT[pulse]["rchan"]:
  1675. canvas.ax1.plot( RSTIMES, 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1676. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " ichan=" + str(ichan))
  1677. canvas.ax1.set_xlabel(r"time [s]", fontsize=8)
  1678. canvas.ax1.set_ylabel(r"signal [nV]", fontsize=8)
  1679. canvas.ax2.set_xlabel(r"time [s]", fontsize=8)
  1680. canvas.ax2.set_ylabel(r"signal [nV]", fontsize=8)
  1681. canvas.ax1.legend(prop={'size':6})
  1682. canvas.ax2.legend(prop={'size':6})
  1683. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1684. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1685. canvas.draw()
  1686. percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/( len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1687. self.progressTrigger.emit(percent)
  1688. iFID += 1
  1689. self.DATADICT[pulse]["TIMES"] = RSTIMES
  1690. #####################################
  1691. # resample pulse data
  1692. for pulse in self.DATADICT["PULSES"]:
  1693. for ipm in range(self.DATADICT["nPulseMoments"]):
  1694. for istack in self.DATADICT["stacks"]:
  1695. ndi = np.shape(self.DATADICT[pulse]["CURRENT"][ipm][istack])[0]%dec
  1696. if ndi:
  1697. [self.DATADICT[pulse]["CURRENT"][ipm][istack], RSPTIMES] = signal.resample(self.DATADICT[pulse]["CURRENT"][ipm][istack][0:-ndi],\
  1698. len(self.DATADICT[pulse]["CURRENT"][ipm][istack][0:-ndi])//dec,\
  1699. self.DATADICT[pulse]["PULSE_TIMES"][0:-ndi], window='hamm')
  1700. else:
  1701. [self.DATADICT[pulse]["CURRENT"][ipm][istack], RSPTIMES] = signal.resample(self.DATADICT[pulse]["CURRENT"][ipm][istack],\
  1702. len(self.DATADICT[pulse]["CURRENT"][ipm][istack])//dec,\
  1703. self.DATADICT[pulse]["PULSE_TIMES"], window='hamm')
  1704. self.DATADICT[pulse]["PULSE_TIMES"] = RSPTIMES
  1705. self.doneTrigger.emit()
  1706. self.updateProcTrigger.emit()
  1707. def computeWindow(self, pulse, band, centre, ftype, canvas=None):
  1708. # Compute window
  1709. nd = len(self.DATADICT[pulse][self.DATADICT[pulse]["chan"][0]][0][self.DATADICT["stacks"][0]])
  1710. fft1 = np.fft.rfft(self.DATADICT[pulse][self.DATADICT[pulse]["chan"][0]][0][self.DATADICT["stacks"][0]])
  1711. freqs = np.fft.fftfreq(nd, self.dt)
  1712. df = freqs[1] - freqs[0]
  1713. N = int((round)(band/df))
  1714. if ftype == "Hamming":
  1715. window = np.hamming(N)
  1716. elif ftype == "Hanning":
  1717. window = np.hanning(N)
  1718. elif ftype == "Rectangular":
  1719. window = np.ones(N)
  1720. elif ftype == "Flat top":
  1721. window = signal.flattop(N)
  1722. else:
  1723. print ("in windowFilter, window type undefined")
  1724. WINDOW = np.zeros(len(fft1))
  1725. ifreq = int(round(centre/df))
  1726. istart = ifreq-len(window)//2
  1727. iend = 0
  1728. if N%2:
  1729. WINDOW[ifreq-N//2:ifreq+N//2+1] = window
  1730. iend = ifreq+N//2+1
  1731. else:
  1732. WINDOW[ifreq-N//2:ifreq+N//2] = window
  1733. iend = ifreq+N//2
  1734. self.WINDOW = WINDOW
  1735. self.iWindowStart = istart
  1736. self.iWindowEnd = iend
  1737. self.FFTtimes = nd
  1738. fft1 = np.fft.irfft(WINDOW)
  1739. # calculate dead time
  1740. self.windead = 0.
  1741. for ift in np.arange(100,0,-1):
  1742. #print( ift, fft1[ift] )
  1743. if fft1[ift] > .001:
  1744. #print ("DEAD TIME", 1e3*self.DATADICT[pulse]["TIMES"][ift] - 1e3*self.DATADICT[pulse]["TIMES"][0] )
  1745. dead = 1e3*self.DATADICT[pulse]["TIMES"][ift] - 1e3*self.DATADICT[pulse]["TIMES"][0]
  1746. self.windead = self.DATADICT[pulse]["TIMES"][ift] - self.DATADICT[pulse]["TIMES"][0]
  1747. break
  1748. if canvas != None:
  1749. canvas.fig.clear()
  1750. canvas.ax1 = canvas.fig.add_axes([.1, .6, .75, .35])
  1751. canvas.ax2 = canvas.fig.add_axes([.1, .1, .75, .35])
  1752. canvas.ax1.plot(WINDOW)
  1753. canvas.ax2.plot( 1e3* self.DATADICT[pulse]["TIMES"][0:100] - 1e3*self.DATADICT[pulse]["TIMES"][0], fft1[0:100] )
  1754. canvas.ax2.set_xlabel("time (ms)")
  1755. canvas.ax2.set_title("IFFT")
  1756. canvas.draw()
  1757. return [WINDOW, nd, istart, iend, dead]
  1758. def windowFilter(self, ftype, band, centre, canvas):
  1759. ###############################
  1760. # Window Filter (Ormsby filter http://www.xsgeo.com/course/filt.htm)
  1761. # apply window
  1762. iFID = 0
  1763. for pulse in self.DATADICT["PULSES"]:
  1764. [WINDOW, nd, istart, iend,dead] = self.computeWindow(pulse, band, centre, ftype)
  1765. for istack in self.DATADICT["stacks"]:
  1766. for ipm in range(self.DATADICT["nPulseMoments"]):
  1767. for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1768. fft = np.fft.rfft( self.DATADICT[pulse][ichan][ipm][istack] )
  1769. fft *= WINDOW
  1770. self.DATADICT[pulse][ichan][ipm][istack] = np.fft.irfft(fft , nd)
  1771. percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/(len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1772. self.progressTrigger.emit(percent)
  1773. iFID += 1
  1774. self.plotFT(canvas, istart, iend)
  1775. self.doneTrigger.emit()
  1776. def bandpassFilter(self, canvas, blank, plot=True):
  1777. if plot:
  1778. canvas.reAx2()
  1779. canvas.ax1.tick_params(axis='both', which='major', labelsize=8)
  1780. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1781. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1782. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1783. ife = (int)( max(self.fe, self.windead) * self.samp )
  1784. # Data
  1785. iFID = 0
  1786. for pulse in self.DATADICT["PULSES"]:
  1787. self.DATADICT[pulse]["TIMES"] = self.DATADICT[pulse]["TIMES"][ife:-ife]
  1788. for ipm in range(self.DATADICT["nPulseMoments"]):
  1789. for istack in self.DATADICT["stacks"]:
  1790. canvas.ax1.clear()
  1791. canvas.ax2.clear()
  1792. #for ichan in np.append(self.DATADICT[pulse]["chan"], self.DATADICT[pulse]["rchan"]):
  1793. for ichan in self.DATADICT[pulse]["rchan"]:
  1794. # reflect signal back on itself to reduce gibbs effects on early times
  1795. #nr = len( self.DATADICT[pulse][ichan][ipm][istack] ) - 1 + ife
  1796. #refl = np.append( -1*self.DATADICT[pulse][ichan][ipm][istack][::-1][0:-1], self.DATADICT[pulse][ichan][ipm][istack] )
  1797. #reflfilt = signal.filtfilt( self.filt_b, self.filt_a, refl )
  1798. #self.DATADICT[pulse][ichan][ipm][istack] = reflfilt[nr:-ife]
  1799. # don't reflect
  1800. self.DATADICT[pulse][ichan][ipm][istack] = \
  1801. signal.filtfilt(self.filt_b, self.filt_a, self.DATADICT[pulse][ichan][ipm][istack])[ife:-ife]
  1802. # plot
  1803. if plot:
  1804. canvas.ax1.plot( self.DATADICT[pulse]["TIMES"], 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1805. label = pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " rchan=" + str(ichan))
  1806. for ichan in self.DATADICT[pulse]["chan"]:
  1807. # reflect signal back on itself to reduce gibbs effects on early times
  1808. #nr = len( self.DATADICT[pulse][ichan][ipm][istack] ) - 1 + ife
  1809. #refl = np.append( -1*self.DATADICT[pulse][ichan][ipm][istack][::-1][0:-1], self.DATADICT[pulse][ichan][ipm][istack] )
  1810. #reflfilt = signal.filtfilt( self.filt_b, self.filt_a, refl )
  1811. #self.DATADICT[pulse][ichan][ipm][istack] = reflfilt[nr:-ife]
  1812. # don't reflect
  1813. self.DATADICT[pulse][ichan][ipm][istack] = \
  1814. scipy.signal.filtfilt(self.filt_b, self.filt_a, self.DATADICT[pulse][ichan][ipm][istack])[ife:-ife]
  1815. # plot
  1816. if plot:
  1817. canvas.ax2.plot( self.DATADICT[pulse]["TIMES"], 1e9*self.DATADICT[pulse][ichan][ipm][istack], \
  1818. label = "data " + pulse + " ipm=" + str(ipm) + " istack=" + str(istack) + " chan=" + str(ichan))
  1819. if plot:
  1820. canvas.ax1.set_xlabel(r"time [s]", fontsize=8)
  1821. canvas.ax1.set_ylabel(r"signal [nV]", fontsize=8)
  1822. canvas.ax2.set_xlabel(r"time [s]", fontsize=8)
  1823. canvas.ax2.set_ylabel(r"signal [nV]", fontsize=8)
  1824. canvas.ax1.legend(prop={'size':6})
  1825. canvas.ax2.legend(prop={'size':6})
  1826. canvas.draw()
  1827. percent = (int)(1e2*((float)(iFID*self.DATADICT["nPulseMoments"]+(ipm))/(len(self.DATADICT["PULSES"])*self.nPulseMoments)))
  1828. self.progressTrigger.emit(percent)
  1829. iFID += 1
  1830. self.doneTrigger.emit()
  1831. self.updateProcTrigger.emit()
  1832. def loadGMRBinaryFID( self, rawfname, istack ):
  1833. """ Reads a single binary GMR file and fills into DATADICT
  1834. """
  1835. #################################################################################
  1836. # figure out key data indices
  1837. # Pulse
  1838. nps = (int)((self.prePulseDelay)*self.samp)
  1839. npul = (int)(self.pulseLength[0]*self.samp) #+ 100
  1840. # Data
  1841. nds = nps+npul+(int)((self.deadTime)*self.samp); # indice pulse 1 data starts
  1842. nd1 = (int)(1.*self.samp) # samples in first pulse
  1843. invGain = 1./self.RxGain
  1844. invCGain = self.CurrentGain
  1845. pulse = "Pulse 1"
  1846. chan = self.DATADICT[pulse]["chan"]
  1847. rchan = self.DATADICT[pulse]["rchan"]
  1848. rawFile = open( rawfname, 'rb')
  1849. for ipm in range(self.nPulseMoments):
  1850. buf1 = rawFile.read(4)
  1851. buf2 = rawFile.read(4)
  1852. N_chan = struct.unpack('>i', buf1 )[0]
  1853. N_samp = struct.unpack('>i', buf2 )[0]
  1854. T = N_samp * self.dt
  1855. TIMES = np.arange(0, T, self.dt) - .0002 # small offset in GMR DAQ?
  1856. DATA = np.zeros([N_samp, N_chan+1])
  1857. for ichan in range(N_chan):
  1858. DATADUMP = rawFile.read(4*N_samp)
  1859. for irec in range(N_samp):
  1860. DATA[irec,ichan] = struct.unpack('>f', DATADUMP[irec*4:irec*4+4])[0]
  1861. # Save into Data Cube
  1862. for ichan in chan:
  1863. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,eval(ichan)+3][nds:nds+nd1] * invGain
  1864. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1865. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,1][nps:nps+npul] * invCGain
  1866. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  1867. # reference channels?
  1868. for ichan in rchan:
  1869. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,eval(ichan)+3][nds:nds+nd1] * invGain
  1870. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1871. def loadGMRASCIIFID( self, rawfname, istack ):
  1872. """Based on the geoMRI instrument manufactured by VistaClara. Imports
  1873. a suite of raw .lvm files with the following format (on one line)
  1874. time(s) DC_Bus/100(V) Current+/75(A) Curr-/75(A) Voltage+/200(V) \
  1875. Ch1(V) Ch2(V) Ch3(V) Ch4(V)
  1876. Sampling rate is assumed at 50 kHz
  1877. """
  1878. import pandas as pd
  1879. #################################################################################
  1880. # figure out key data indices
  1881. # Pulse
  1882. nps = (int)((self.prePulseDelay)*self.samp)
  1883. npul = (int)(self.pulseLength[0]*self.samp) #+ 100
  1884. # Data
  1885. nds = nps+npul+(int)((self.deadTime)*self.samp); # indice pulse 1 data starts
  1886. nd1 = (int)(1.*self.samp) - nds # samples in first pulse
  1887. ndr = (int)(1.*self.samp) # samples in record
  1888. invGain = 1./self.RxGain
  1889. invCGain = self.CurrentGain
  1890. pulse = "Pulse 1"
  1891. chan = self.DATADICT[pulse]["chan"]
  1892. rchan = self.DATADICT[pulse]["rchan"]
  1893. T = 1.5 #N_samp * self.dt
  1894. TIMES = np.arange(0, T, self.dt) - .0002 # small offset in GMR DAQ?
  1895. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  1896. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  1897. # pandas is much faster than numpy for io
  1898. #DATA = np.loadtxt(rawfname)
  1899. DATA = pd.read_csv(rawfname, header=None, sep="\t").values
  1900. for ipm in range(self.nPulseMoments):
  1901. for ichan in np.append(chan,rchan):
  1902. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:, eval(ichan)+4][nds:(nds+nd1)] * invGain
  1903. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,2][nps:nps+npul] * invCGain
  1904. nds += ndr
  1905. nps += ndr
  1906. def loadFIDData(self, base, procStacks, chanin, rchanin, FIDProc, canvas, deadTime, plot):
  1907. '''
  1908. Loads a GMR FID dataset, reads binary and ASCII format files
  1909. '''
  1910. canvas.reAx3(True,False)
  1911. chan = []
  1912. for ch in chanin:
  1913. chan.append(str(ch))
  1914. rchan = []
  1915. for ch in rchanin:
  1916. rchan.append(str(ch))
  1917. # not in any headers but this has changed, NOT the place to do this. MOVE
  1918. #self.prePulseDelay = 0.01 # delay before pulse
  1919. self.deadTime = deadTime # instrument dead time before measurement
  1920. self.samp = 50000. # in case this is a reproc, these might have
  1921. self.dt = 1./self.samp # changed
  1922. #################################################################################
  1923. # Data structures
  1924. PULSES = [FIDProc]
  1925. PULSES = ["Pulse 1"]
  1926. self.DATADICT = {}
  1927. self.DATADICT["nPulseMoments"] = self.nPulseMoments
  1928. self.DATADICT["stacks"] = procStacks
  1929. self.DATADICT["PULSES"] = PULSES
  1930. for pulse in PULSES:
  1931. self.DATADICT[pulse] = {}
  1932. self.DATADICT[pulse]["chan"] = chan # TODO these should not be a subet of pulse! for GMR all
  1933. self.DATADICT[pulse]["rchan"] = rchan # data are consistent
  1934. self.DATADICT[pulse]["CURRENT"] = {}
  1935. for ichan in np.append(chan,rchan):
  1936. self.DATADICT[pulse][ichan] = {}
  1937. for ipm in range(self.nPulseMoments):
  1938. self.DATADICT[pulse][ichan][ipm] = {}
  1939. self.DATADICT[pulse]["CURRENT"][ipm] = {}
  1940. for istack in procStacks:
  1941. self.DATADICT[pulse][ichan][ipm][istack] = np.zeros(3)
  1942. self.DATADICT[pulse]["CURRENT"][ipm][istack] = np.zeros(3)
  1943. ##############################################
  1944. # Read in binary (.lvm) data
  1945. iistack = 0
  1946. fnames = []
  1947. for istack in procStacks:
  1948. if self.nDAQVersion < 2.3:
  1949. #rawfname = base + "_" + str(istack)
  1950. self.loadGMRASCIIFID( base + "_" + str(istack), istack )
  1951. else:
  1952. self.loadGMRBinaryFID( base + "_" + str(istack) + ".lvm", istack )
  1953. #fnames.append( base + "_" + str(istack) + ".lvm" )
  1954. percent = (int) (1e2*((float)((iistack*self.nPulseMoments+ipm+1)) / (len(procStacks)*self.nPulseMoments)))
  1955. self.progressTrigger.emit(percent)
  1956. iistack += 1
  1957. # multiprocessing load data
  1958. #info = {}
  1959. #info["prePulseDelay"] = self.prePulseDelay
  1960. #with multiprocessing.Pool() as pool:
  1961. # 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))
  1962. # Plotting
  1963. if plot:
  1964. iistack = 0
  1965. for istack in procStacks:
  1966. for ipm in range(self.nPulseMoments):
  1967. canvas.ax1.clear()
  1968. canvas.ax2.clear()
  1969. canvas.ax3.clear()
  1970. #canvas.fig.patch.set_facecolor('blue')
  1971. for ichan in chan:
  1972. canvas.ax1.plot(self.DATADICT["Pulse 1"]["PULSE_TIMES"], self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] , color='black')
  1973. 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')
  1974. for ichan in rchan:
  1975. 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')
  1976. canvas.ax3.legend(prop={'size':6})
  1977. canvas.ax2.legend(prop={'size':6})
  1978. canvas.ax1.set_title("stack "+str(istack)+" pulse index " + str(ipm), fontsize=8)
  1979. canvas.ax1.set_xlabel("time [s]", fontsize=8)
  1980. canvas.ax1.set_ylabel("Current [A]", fontsize=8)
  1981. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1982. canvas.ax2.set_ylabel("RAW signal [V]", fontsize=8)
  1983. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  1984. canvas.ax2.tick_params(axis='both', which='minor', labelsize=6)
  1985. canvas.ax2.set_xlabel("time [s]", fontsize=8)
  1986. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1987. canvas.ax3.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  1988. canvas.draw()
  1989. percent = (int) (1e2*((float)((iistack*self.nPulseMoments+ipm+1)) / (len(procStacks)*self.nPulseMoments)))
  1990. self.progressTrigger.emit(percent)
  1991. iistack += 1
  1992. self.enableDSP()
  1993. self.doneTrigger.emit()
  1994. def load4PhaseT1Data(self, base, procStacks, chan, rchan, FIDProc, canvas, deadTime, plot):
  1995. """
  1996. Designed to load GMR 4-phase data which use the following convention for phase cycles
  1997. P1 P2
  1998. Stack 1 -> 0 0 <-- <--
  1999. Stack 2 -> 0 pi/2 | <-- <--
  2000. Stack 3 -> pi/2 0 <-- | <--
  2001. Stack 4 -> pi/2 pi/2 <-- <--
  2002. The cycle is determined by stack indice. Walbrecker proposes for pulse2 data (Stack2 - Stack1) / 2
  2003. equivalently (Stack 4 - Stack3) will yield the same voltage response wrt. the second pulse.
  2004. 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
  2005. Then there are just the two phase cycles that can be stacked like normal.
  2006. Unfortunately, we need to stack each cycle first, then perform corrections for phase cycling. The reason for this is that otherwise,
  2007. 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,
  2008. if there is an uneven number of a certain phase cycle.
  2009. We could, I suppose impose this condition, but I think I would rather not?
  2010. + more samples for std. deviation calculation
  2011. + single spikes will have less residual effect
  2012. - can no longer do normality tests etc. and remove data that are suspect.
  2013. - requires a dumb stack, and may also require removal of entire stacks of data
  2014. 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 ...
  2015. This however, is altered by the above convention. It gets a little complicated...
  2016. """
  2017. import struct
  2018. canvas.reAx2()
  2019. # not in any headers but this has changed, NOT the place to do this. MOVE
  2020. self.prePulseDelay = 0.01 # delay before pulse
  2021. self.deadTime = deadTime # instrument dead time before measurement
  2022. self.samp = 50000. # in case this is a reproc, these might have
  2023. self.dt = 1./self.samp # changed
  2024. invGain = 1./self.RxGain
  2025. invCGain = self.CurrentGain
  2026. #################################################################################
  2027. # figure out key data indices
  2028. # Pulse
  2029. nps = (int)((self.prePulseDelay)*self.samp)
  2030. nps2 = (int)((self.prePulseDelay+self.interpulseDelay)*self.samp)
  2031. npul = (int)(self.pulseLength[0]*self.samp) #+ 100
  2032. np2 = (int)(self.pulseLength[1]*self.samp) #+ 100
  2033. # Data
  2034. nds = nps+npul+(int)((self.deadTime)*self.samp); # indice pulse 1 data starts
  2035. nd1 = (int)((self.interpulseDelay)*self.samp) # samples in first pulse
  2036. nd2s = nps+npul+nd1+(int)((self.deadTime)*self.samp); # indice pulse 2 data starts
  2037. nd2 = (int)((1.)*self.samp) # samples in first pulse
  2038. nd1 -= (int)((.028)*self.samp) + nps # some time to get ready for next pulse
  2039. #################################################################################
  2040. # Data structures
  2041. PULSES = [FIDProc]
  2042. if FIDProc == "Both":
  2043. PULSES = ["Pulse 1","Pulse 2"]
  2044. self.DATADICT = {}
  2045. self.DATADICT["nPulseMoments"] = self.nPulseMoments
  2046. self.DATADICT["stacks"] = procStacks
  2047. self.DATADICT["PULSES"] = PULSES
  2048. for pulse in PULSES:
  2049. self.DATADICT[pulse] = {}
  2050. self.DATADICT[pulse]["chan"] = chan
  2051. self.DATADICT[pulse]["rchan"] = rchan
  2052. self.DATADICT[pulse]["CURRENT"] = {}
  2053. for ichan in np.append(chan,rchan):
  2054. self.DATADICT[pulse][ichan] = {}
  2055. for ipm in range(self.nPulseMoments):
  2056. self.DATADICT[pulse][ichan][ipm] = {}
  2057. self.DATADICT[pulse]["CURRENT"][ipm] = {}
  2058. for istack in procStacks:
  2059. self.DATADICT[pulse][ichan][ipm][istack] = np.zeros(3)
  2060. self.DATADICT[pulse]["CURRENT"][ipm][istack] = np.zeros(3)
  2061. ##############################################
  2062. # Read in binary data
  2063. iistack = 0
  2064. for istack in procStacks:
  2065. rawFile = open(base + "_" + str(istack) + ".lvm", 'rb')
  2066. for ipm in range(self.nPulseMoments):
  2067. N_chan = struct.unpack('>i', rawFile.read(4))[0]
  2068. N_samp = struct.unpack('>i', rawFile.read(4))[0]
  2069. T = N_samp * self.dt
  2070. TIMES = np.arange(0, T, self.dt) - .0002 # small offset in GMR DAQ?
  2071. DATA = np.zeros([N_samp, N_chan+1])
  2072. for ichan in range(N_chan):
  2073. DATADUMP = rawFile.read(4*N_samp)
  2074. for irec in range(N_samp):
  2075. DATA[irec,ichan] = struct.unpack('>f', DATADUMP[irec*4:irec*4+4])[0]
  2076. if plot:
  2077. canvas.ax1.clear()
  2078. canvas.ax2.clear()
  2079. li = np.shape( DATA[:,4][nd2s:nd2s+nd2] )[0]
  2080. ######################################
  2081. # save into DATA cube
  2082. # TODO, changing iFID to 'Pulse 1' or 'Pulse 2'
  2083. for ichan in chan:
  2084. if FIDProc == "Pulse 1":
  2085. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  2086. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  2087. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,1][nps:nps+npul] * invCGain
  2088. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  2089. if plot:
  2090. 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')
  2091. canvas.ax2.plot(self.DATADICT["Pulse 1"]["PULSE_TIMES"], self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] , color='black')
  2092. elif FIDProc == "Pulse 2":
  2093. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] *invGain
  2094. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  2095. self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack] = DATA[:,1][nps2:nps2+np2] * invCGain
  2096. self.DATADICT["Pulse 2"]["PULSE_TIMES"] = TIMES[nps2:nps2+np2]
  2097. if plot:
  2098. 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')
  2099. canvas.ax2.plot( self.DATADICT["Pulse 2"]["PULSE_TIMES"], self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack], color='black' )
  2100. else:
  2101. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  2102. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] * invGain
  2103. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  2104. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  2105. self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] = DATA[:,1][nps:nps+npul] * invCGain
  2106. self.DATADICT["Pulse 1"]["PULSE_TIMES"] = TIMES[nps:nps+npul]
  2107. self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack] = DATA[:,1][nps2:nps2+np2] * invCGain
  2108. self.DATADICT["Pulse 2"]["PULSE_TIMES"] = TIMES[nps2:nps2+np2]
  2109. if plot:
  2110. 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')
  2111. 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')
  2112. canvas.ax2.plot( self.DATADICT["Pulse 1"]["PULSE_TIMES"], self.DATADICT["Pulse 1"]["CURRENT"][ipm][istack] , color='black' )
  2113. canvas.ax2.plot( self.DATADICT["Pulse 2"]["PULSE_TIMES"], self.DATADICT["Pulse 2"]["CURRENT"][ipm][istack] , color='black')
  2114. for ichan in rchan:
  2115. if FIDProc == "Pulse 1":
  2116. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  2117. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  2118. if plot:
  2119. 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')
  2120. elif FIDProc == "Pulse 2":
  2121. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] * invGain
  2122. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  2123. if plot:
  2124. 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')
  2125. else:
  2126. self.DATADICT["Pulse 1"][ichan][ipm][istack] = DATA[:,ichan+3][nds:nds+nd1] * invGain
  2127. self.DATADICT["Pulse 2"][ichan][ipm][istack] = DATA[:,ichan+3][nd2s:nd2s+nd2] * invGain
  2128. self.DATADICT["Pulse 1"]["TIMES"] = TIMES[nds:nds+nd1]
  2129. self.DATADICT["Pulse 2"]["TIMES"] = TIMES[nd2s:nd2s+nd2]
  2130. if plot:
  2131. 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')
  2132. 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')
  2133. if plot:
  2134. canvas.ax1.legend(prop={'size':6})
  2135. canvas.ax1.set_title("stack "+str(istack)+" pulse index " + str(ipm), fontsize=8)
  2136. canvas.ax1.set_xlabel("time [s]", fontsize=8)
  2137. canvas.ax1.set_ylabel("RAW signal [V]", fontsize=8)
  2138. canvas.ax2.set_ylabel("Current [A]", fontsize=8)
  2139. canvas.ax2.tick_params(axis='both', which='major', labelsize=8)
  2140. canvas.ax2.tick_params(axis='both', which='minor', labelsize=6)
  2141. canvas.ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  2142. canvas.ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
  2143. canvas.draw()
  2144. # update GUI of where we are
  2145. percent = (int) (1e2*((float)((iistack*self.nPulseMoments+ipm+1)) / (len(procStacks)*self.nPulseMoments)))
  2146. self.progressTrigger.emit(percent)
  2147. iistack += 1
  2148. self.enableDSP()
  2149. self.doneTrigger.emit()
  2150. if __name__ == "__main__":
  2151. if len(sys.argv) < 4:
  2152. print( "mrsurvey path/to/header <stack1> <stackN> ")
  2153. exit()
  2154. GMR = GMRDataProcessor()
  2155. GMR.readHeaderFile(sys.argv[1])
  2156. GMR.Print()
  2157. if GMR.pulseType == "FID":
  2158. GMR.loadFIDData(sys.argv[1], sys.argv[2], sys.argv[3], 5)
  2159. if GMR.pulseType == "4PhaseT1":
  2160. GMR.load4PhaseT1Data(sys.argv[1], sys.argv[2], sys.argv[3], 5)
  2161. pylab.show()