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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976
  1. #/usr/bin/env python
  2. import sys
  3. import matplotlib
  4. matplotlib.use("QT5Agg")
  5. from PyQt5 import QtCore, QtGui, QtWidgets #, uic
  6. import numpy as np
  7. import time
  8. import os
  9. from copy import deepcopy
  10. from matplotlib.backends.backend_qt5 import NavigationToolbar2QT #as NavigationToolbar
  11. import datetime, time
  12. import pkg_resources # part of setuptools
  13. from collections import OrderedDict
  14. from ruamel import yaml
  15. from akvo.gui.main_ui import Ui_MainWindow
  16. from akvo.gui.addCircularLoop_ui import Ui_circularLoopAdd
  17. from akvo.gui.addFigure8Loop_ui import Ui_figure8LoopAdd
  18. from akvo.gui.addPolygonalLoop_ui import Ui_polygonalLoopAdd
  19. from akvo.gui.redirect_ui import Ui_callScript
  20. from akvo.gui.callScript import callScript
  21. from akvo.tressel import mrsurvey
  22. from pyLemma import LemmaCore
  23. from pyLemma import FDEM1D
  24. from pyLemma import Merlin
  25. VERSION = pkg_resources.require("Akvo")[0].version
  26. GAMMAH = 42.577478518 * 1e-3 # Hz nT
  27. # Writes out numpy arrays into Eigen vectors as serialized by Lemma
  28. class MatrixXr(yaml.YAMLObject):
  29. yaml_tag = u'MatrixXr'
  30. def __init__(self, rows, cols, data):
  31. self.rows = rows
  32. self.cols = cols
  33. self.data = np.zeros((rows,cols))
  34. def __repr__(self):
  35. return "%s(rows=%r, cols=%r, data=%r)" % (self.__class__.__name__, self.rows, self.cols, self.data)
  36. class VectorXr(yaml.YAMLObject):
  37. yaml_tag = r'VectorXr'
  38. def __init__(self, array):
  39. self.size = np.shape(array)[0]
  40. self.data = array.tolist()
  41. def __repr__(self):
  42. # Converts to numpy array on import
  43. return "np.array(%r)" % (self.data)
  44. def setup_yaml():
  45. """ https://stackoverflow.com/a/8661021 """
  46. represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items())
  47. yaml.add_representer(OrderedDict, represent_dict_order)
  48. setup_yaml()
  49. class AkvoYamlNode(yaml.YAMLObject):
  50. yaml_tag = u'AkvoData'
  51. def __init__(self):
  52. self.Akvo_VERSION = VERSION
  53. self.Import = OrderedDict() # {}
  54. self.Processing = [] # OrderedDict()
  55. self.Stacking = OrderedDict()
  56. self.META = OrderedDict()
  57. def __repr__(self):
  58. return "%s(name=%r, Akvo_VERSION=%r, Import=%r, Processing=%r, self.Stacking=%r, self.META=%r)" % (
  59. self.__class__.__name__, self.Akvo_VERSION, self.Import, self.Processing, self.Stacking, self.META )
  60. try:
  61. import thread
  62. except ImportError:
  63. import _thread as thread #Py3K compatibility
  64. class MyPopup(QtWidgets.QWidget):
  65. def __init__(self, name):
  66. super().__init__()
  67. self.name = name
  68. self.initUI()
  69. def initUI(self):
  70. lblName = QtWidgets.QLabel(self.name, self)
  71. class ApplicationWindow(QtWidgets.QMainWindow):
  72. def __init__(self):
  73. super().__init__()
  74. #QtWidgets.QMainWindow.__init__(self)
  75. self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
  76. # alternative to calling pyuic
  77. #self.ui = uic.loadUi('main.ui', self)
  78. self.ui = Ui_MainWindow()
  79. self.ui.setupUi(self)
  80. self.RAWDataProc = None
  81. self.YamlNode = AkvoYamlNode()
  82. # initialise some stuff
  83. self.ui.lcdNumberTauPulse2.setEnabled(0)
  84. self.ui.lcdNumberTauPulse1.setEnabled(0)
  85. self.ui.lcdNumberNuTx.setEnabled(0)
  86. self.ui.lcdNumberTuneuF.setEnabled(0)
  87. self.ui.lcdNumberSampFreq.setEnabled(0)
  88. self.ui.lcdNumberTauDelay.setEnabled(0)
  89. self.ui.lcdNumberNQ.setEnabled(0)
  90. self.logText = []
  91. #######################
  92. ##################### #
  93. ## Make connections # #
  94. ##################### #
  95. #######################
  96. ##############
  97. # Menu items #
  98. ##############
  99. self.ui.actionOpen_GMR.triggered.connect(self.openGMRRAWDataset)
  100. self.ui.actionSave_Preprocessed_Dataset.triggered.connect(self.SavePreprocess)
  101. self.ui.actionExport_Preprocessed_Dataset.triggered.connect(self.ExportPreprocess)
  102. self.ui.actionExport_Preprocessed_Dataset.setEnabled(False)
  103. self.ui.actionOpen_Preprocessed_Dataset.triggered.connect(self.OpenPreprocess)
  104. self.ui.actionAboutAkvo.triggered.connect(self.about)
  105. ###########
  106. # Buttons #
  107. ###########
  108. self.ui.loadDataPushButton.pressed.connect(self.loadRAW)
  109. self.ui.sumDataGO.pressed.connect( self.sumDataChans )
  110. self.ui.bandPassGO.pressed.connect( self.bandPassFilter )
  111. self.ui.filterDesignPushButton.pressed.connect( self.designFilter )
  112. self.ui.fdDesignPushButton.pressed.connect( self.designFDFilter )
  113. self.ui.downSampleGO.pressed.connect( self.downsample )
  114. self.ui.windowFilterGO.pressed.connect( self.windowFilter )
  115. self.ui.adaptGO.pressed.connect( self.adaptFilter )
  116. self.ui.adaptFDGO.pressed.connect( self.adaptFilterFD )
  117. self.ui.qdGO.pressed.connect( self.quadDet )
  118. self.ui.gateIntegrateGO.pressed.connect( self.gateIntegrate )
  119. self.ui.calcQGO.pressed.connect( self.calcQ )
  120. self.ui.FDSmartStackGO.pressed.connect( self.FDSmartStack )
  121. self.ui.harmonicGO.pressed.connect( self.harmonicModel )
  122. self.ui.K0Data.pressed.connect( self.K0DataSelect )
  123. self.ui.invDataButton.pressed.connect( self.invDataSelect )
  124. self.ui.invKernelButton.pressed.connect( self.invKernelSelect )
  125. self.ui.f0K1Spin.valueChanged.connect( self.LCDHarmonics )
  126. self.ui.f0KNSpin.valueChanged.connect( self.LCDHarmonics )
  127. self.ui.f0KsSpin.valueChanged.connect( self.LCDHarmonics )
  128. self.ui.f0Spin.valueChanged.connect( self.LCDHarmonics )
  129. self.ui.NHarmonicsFreqsSpin.valueChanged.connect( self.LCDHarmonics2 )
  130. self.ui.f1K1Spin.valueChanged.connect( self.LCDHarmonics2 )
  131. self.ui.f1KNSpin.valueChanged.connect( self.LCDHarmonics2 )
  132. self.ui.f1KsSpin.valueChanged.connect( self.LCDHarmonics2 )
  133. self.ui.f1Spin.valueChanged.connect( self.LCDHarmonics2 )
  134. self.ui.plotQD.setEnabled(False)
  135. self.ui.plotQD.pressed.connect( self.plotQD )
  136. self.ui.plotGI.setEnabled(False)
  137. self.ui.plotGI.pressed.connect( self.plotGI )
  138. # balance the Larmor frequency info and Tx off resonance info
  139. self.ui.intensitySpinBox.valueChanged.connect( self.adjustLarmor )
  140. self.ui.txv.valueChanged.connect( self.adjustB0 )
  141. self.ui.larmorv.valueChanged.connect( self.adjustB02 )
  142. # Kernel
  143. self.ui.calcK0.pressed.connect( self.calcK0 )
  144. # Inversion
  145. self.ui.invertButton.pressed.connect( self.QTInv )
  146. # META
  147. self.ui.locEdit.editingFinished.connect( self.logSite )
  148. self.ui.UTMzone.currentIndexChanged.connect( self.logSite )
  149. self.ui.latBand.currentIndexChanged.connect( self.logSite )
  150. self.ui.ellipsoid.currentIndexChanged.connect( self.logSite )
  151. self.ui.incSpinBox.valueChanged.connect( self.logSite )
  152. self.ui.decSpinBox.valueChanged.connect( self.logSite )
  153. self.ui.intensitySpinBox.valueChanged.connect( self.logSite )
  154. self.ui.tempSpinBox.valueChanged.connect( self.logSite )
  155. self.ui.timeEdit.timeChanged.connect( self.logSite )
  156. self.ui.dateEdit.dateChanged.connect( self.logSite )
  157. # this may call the yaml stuff too often...
  158. self.ui.txtComments.textChanged.connect( self.logSite )
  159. self.ui.plotLoops.pressed.connect( self.plotLoops2 )
  160. self.ui.removeLoopButton.pressed.connect( self.removeLoop )
  161. # Loops
  162. self.ui.addLoopButton.pressed.connect( self.loopAdd )
  163. self.loops = {}
  164. # hide header info box
  165. #self.ui.headerFileBox.setVisible(False)
  166. self.ui.headerFileBox.clicked.connect( self.headerBoxShrink )
  167. self.ui.headerBox2.setVisible(False)
  168. # Clean up the tab widget
  169. self.ui.actionPreprocessing.triggered.connect(self.addPreProc)
  170. self.ui.actionModelling.triggered.connect(self.addModelling)
  171. self.ui.actionInversion.triggered.connect(self.addInversion)
  172. # tabs
  173. #self.ui.ProcTabs.tabCloseRequested.connect( self.closeTabs )
  174. #self.ui.ProcTabs.tabBar().setTabButton(7, QtWidgets.QTabBar.RightSide,None)
  175. self.ui.ProcTabs.removeTab(4)
  176. self.ui.ProcTabs.removeTab(4)
  177. self.ui.ProcTabs.removeTab(4)
  178. self.ui.ProcTabs.removeTab(4)
  179. #self.ui.LoadTab.close( )
  180. # Add progressbar to statusbar
  181. self.ui.barProgress = QtWidgets.QProgressBar()
  182. self.ui.statusbar.addPermanentWidget(self.ui.barProgress, 0);
  183. self.ui.barProgress.setMaximumSize(100, 16777215);
  184. self.ui.barProgress.hide();
  185. self.ui.mplwidget_navigator.setCanvas(self.ui.mplwidget)
  186. #self.ui.mplwidget_navigator_2.setCanvas(self.ui.mplwidget)
  187. self.ui.txRxTable.setColumnCount(4)
  188. self.ui.txRxTable.setRowCount(0)
  189. self.ui.txRxTable.setHorizontalHeaderLabels( ["Label", "Geom.","Turns","Tx/Rx"] )
  190. ##########################################################################
  191. # layer Table
  192. self.ui.layerTableWidget.setRowCount(80)
  193. self.ui.layerTableWidget.setColumnCount(3)
  194. self.ui.layerTableWidget.setHorizontalHeaderLabels( [r"top [m]", r"bottom [m]", "ρ [Ωm]" ] )
  195. # do we want this
  196. self.ui.layerTableWidget.setDragDropOverwriteMode(False)
  197. self.ui.layerTableWidget.setDragEnabled(True)
  198. self.ui.layerTableWidget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  199. pCell0 = QtWidgets.QTableWidgetItem()
  200. pCell0.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  201. pCell0.setBackground( QtGui.QColor("lightgrey").lighter(110) )
  202. pCell0.setForeground( QtGui.QColor("black") )
  203. pCell0.setText(str("0"))
  204. self.ui.layerTableWidget.setItem(0, 0, pCell0)
  205. pCell1 = QtWidgets.QTableWidgetItem()
  206. #pCell1.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  207. pCell1.setBackground( QtGui.QColor("lightblue") ) #.lighter(110) )
  208. pCell1.setForeground( QtGui.QColor("black") )
  209. self.ui.layerTableWidget.setItem(0, 1, pCell1)
  210. pCell2 = QtWidgets.QTableWidgetItem()
  211. #pCell1.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  212. pCell2.setBackground( QtGui.QColor("white") ) #.lighter(110) )
  213. pCell2.setForeground( QtGui.QColor("black") )
  214. self.ui.layerTableWidget.setItem(0, 2, pCell2)
  215. for ir in range(1, self.ui.layerTableWidget.rowCount() ):
  216. for ic in range(0, self.ui.layerTableWidget.columnCount() ):
  217. pCell = QtWidgets.QTableWidgetItem()
  218. #pCell.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
  219. pCell.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  220. pCell.setBackground( QtGui.QColor("lightgrey").lighter(110) )
  221. pCell.setForeground( QtGui.QColor("black"))
  222. self.ui.layerTableWidget.setItem(ir, ic, pCell)
  223. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  224. def LCDHarmonics(self):
  225. self.ui.lcdH1F.setEnabled(True)
  226. self.ui.lcdH1F.display( self.ui.f0Spin.value() * self.ui.f0K1Spin.value() )
  227. self.ui.lcdHNF.setEnabled(True)
  228. self.ui.lcdHNF.display( self.ui.f0Spin.value() * self.ui.f0KNSpin.value() )
  229. self.ui.lcdf0NK.setEnabled(True)
  230. self.ui.lcdf0NK.display( (self.ui.f0KNSpin.value()+1-self.ui.f0K1Spin.value()) * self.ui.f0KsSpin.value() )
  231. def LCDHarmonics2(self):
  232. if self.ui.NHarmonicsFreqsSpin.value() == 2:
  233. self.ui.lcdH1F2.setEnabled(True)
  234. self.ui.lcdH1F2.display( self.ui.f1Spin.value() * self.ui.f1K1Spin.value() )
  235. self.ui.lcdHNF2.setEnabled(True)
  236. self.ui.lcdHNF2.display( self.ui.f1Spin.value() * self.ui.f1KNSpin.value() )
  237. self.ui.lcdf0NK2.setEnabled(True)
  238. self.ui.lcdf0NK2.display( (self.ui.f1KNSpin.value()+1-self.ui.f1K1Spin.value()) * self.ui.f1KsSpin.value() )
  239. else:
  240. self.ui.lcdH1F2.setEnabled(False)
  241. self.ui.lcdHNF2.setEnabled(False)
  242. self.ui.lcdf0NK2.setEnabled(False)
  243. def adjustLarmor(self):
  244. """ Triggers when the B0 intensity spin box is cycled
  245. """
  246. self.ui.larmorv.setValue( self.ui.intensitySpinBox.value() * GAMMAH )
  247. self.ui.txv.setValue( self.RAWDataProc.transFreq - self.ui.larmorv.value() )
  248. def adjustB0(self):
  249. """ Triggers when tx frequency offset is cycled
  250. """
  251. self.ui.intensitySpinBox.setValue( (self.RAWDataProc.transFreq - self.ui.txv.value()) / GAMMAH )
  252. def adjustB02(self):
  253. """ Triggers when Larmor frequency spin box is cycled o
  254. """
  255. self.ui.intensitySpinBox.setValue( (self.ui.larmorv.value()) / GAMMAH )
  256. def closeTabs(self):
  257. #self.ui.ProcTabs.removeTab(idx)
  258. self.ui.ProcTabs.clear( )
  259. def addPreProc(self):
  260. if self.ui.actionPreprocessing.isChecked():
  261. self.ui.actionModelling.setChecked(False)
  262. self.ui.actionInversion.setChecked(False)
  263. self.ui.ProcTabs.clear( )
  264. self.ui.ProcTabs.insertTab( 0, self.ui.LoadTab, "Load" )
  265. self.ui.ProcTabs.insertTab( 1, self.ui.NCTab, "Noise removal" )
  266. self.ui.ProcTabs.insertTab( 2, self.ui.QCTab, "QC" )
  267. self.ui.ProcTabs.insertTab( 3, self.ui.METATab, "META" )
  268. self.ui.ProcTabs.insertTab( 4, self.ui.LogTab, "Log" )
  269. else:
  270. self.ui.ProcTabs.removeTab(0)
  271. self.ui.ProcTabs.removeTab(0)
  272. self.ui.ProcTabs.removeTab(0)
  273. self.ui.ProcTabs.removeTab(0)
  274. def addModelling(self):
  275. if self.ui.actionModelling.isChecked():
  276. self.ui.actionPreprocessing.setChecked(False)
  277. self.ui.actionInversion.setChecked(False)
  278. self.ui.ProcTabs.clear( )
  279. self.ui.ProcTabs.insertTab( 0, self.ui.KernTab, "Kernel" )
  280. self.ui.ProcTabs.insertTab( 1, self.ui.ModelTab, "Modelling" )
  281. #self.ui.ProcTabs.insertTab( 2, self.ui.LogTab, "Log" )
  282. else:
  283. self.ui.ProcTabs.removeTab(0)
  284. self.ui.ProcTabs.removeTab(0)
  285. def addInversion(self, idx):
  286. if self.ui.actionInversion.isChecked():
  287. self.ui.actionPreprocessing.setChecked(False)
  288. self.ui.actionModelling.setChecked(False)
  289. self.ui.ProcTabs.clear( )
  290. self.ui.ProcTabs.insertTab( 0, self.ui.InvertTab, "QT Inversion" )
  291. self.ui.ProcTabs.insertTab( 1, self.ui.AppraiseTab, "Appraisal" )
  292. #self.ui.ProcTabs.insertTab( 2, self.ui.LogTab, "Log" )
  293. else:
  294. self.ui.ProcTabs.removeTab(0)
  295. self.ui.ProcTabs.removeTab(0)
  296. def invDataSelect(self):
  297. try:
  298. with open('.akvo.last.path') as f:
  299. fpath = f.readline()
  300. pass
  301. except IOError as e:
  302. fpath = '.'
  303. self.akvoDataFile = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Datafile File', fpath, r"Akvo datafiles (*.akvoProcData *.yaml)")[0]
  304. self.ui.dataText.clear()
  305. self.ui.dataText.append( self.akvoDataFile )
  306. def K0DataSelect(self):
  307. try:
  308. with open('.akvo.last.path') as f:
  309. fpath = f.readline()
  310. pass
  311. except IOError as e:
  312. fpath = '.'
  313. self.K0akvoDataFile = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Datafile File', fpath, r"Akvo datafiles (*.akvoProcData *.yaml)")[0]
  314. # populate combo box with loops
  315. if os.path.isfile( self.K0akvoDataFile ):
  316. self.ui.K0DataText.clear()
  317. self.ui.K0DataText.append( self.K0akvoDataFile )
  318. with open(self.K0akvoDataFile) as f:
  319. parse = yaml.load( f, Loader=yaml.Loader )
  320. self.ui.txListWidget.clear()
  321. self.ui.rxListWidget.clear()
  322. for loop in parse.META["Loops"]:
  323. print(loop)
  324. self.ui.txListWidget.addItem( parse.META["Loops"][loop] )
  325. self.ui.rxListWidget.addItem( parse.META["Loops"][loop] )
  326. # TODO, why are these necessary
  327. self.ui.txListWidget.setCurrentRow(0)
  328. self.ui.rxListWidget.setCurrentRow(0)
  329. # else do nothing
  330. def invKernelSelect(self):
  331. try:
  332. with open('.akvo.last.path') as f:
  333. fpath = f.readline()
  334. pass
  335. except IOError as e:
  336. fpath = '.'
  337. self.K0file = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Kernel File', fpath, r"Akvo kernels (*.akvoK0)")[0]
  338. self.ui.kernelText.clear()
  339. self.ui.kernelText.append(self.K0file)
  340. def QTInv(self):
  341. print("Big RED INVERT BUTTON")
  342. try:
  343. with open('.akvo.last.path') as f:
  344. fpath = f.readline()
  345. pass
  346. except IOError as e:
  347. fpath = '.'
  348. #K0file = self.ui.kernelText.text()
  349. #akvoDataFile = self.ui.dataText.text()
  350. T2lo = self.ui.T2low.value()
  351. T2hi = self.ui.T2hi.value()
  352. NT2 = self.ui.NT2.value()
  353. dataChan = self.ui.invChan.currentText()
  354. t2Obj = self.ui.T2Objective.currentText()
  355. depthObj = self.ui.depthObjective.currentText()
  356. alpha_0 = self.ui.initialAlpha.value()
  357. invDict = dict()
  358. invDict["data"] = dict()
  359. invDict["data"] = dict()
  360. invDict["data"][self.akvoDataFile] = dict()
  361. invDict["data"][self.akvoDataFile]["channels"] = [dataChan,]
  362. invDict["K0"] = [self.K0file,]
  363. invDict["T2Bins"] = dict()
  364. invDict["T2Bins"]["low"] = T2lo
  365. invDict["T2Bins"]["high"] = T2hi
  366. invDict["T2Bins"]["number"] = NT2
  367. node = yaml.YAML()
  368. kpo = open( "invert.yml", 'w' )
  369. node.dump(invDict, kpo)
  370. callBox = callScript( ) #QtWidgets.QDialog()
  371. callBox.ui = Ui_callScript()
  372. callBox.ui.setupUi( callBox )
  373. callBox.setupQTInv( "invert.yml" )
  374. callBox.exec_()
  375. callBox.show()
  376. def calcK0(self):
  377. try:
  378. with open('.akvo.last.path') as f:
  379. fpath = f.readline()
  380. pass
  381. except IOError as e:
  382. fpath = '.'
  383. #self.K0akvoDataFile = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Datafile File', fpath, r"Akvo datafiles (*.yaml)")[0]
  384. #akvoData = QtWidgets.QFileDialog.getOpenFileName(self, 'Open Datafile File', fpath, r"Akvo datafiles (*.yaml)")[0]
  385. txCoilList = self.ui.txListWidget.selectedItems() #currentItem().text()
  386. txCoils = []
  387. for txCoil in txCoilList:
  388. print("txCoil", txCoil.text())
  389. txCoils.append(txCoil.text())
  390. rxCoilList = self.ui.txListWidget.selectedItems() #currentItem().text()
  391. rxCoils = []
  392. for rxCoil in rxCoilList:
  393. print("rxCoil", rxCoil.text())
  394. rxCoils.append(rxCoil.text())
  395. saveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save kernel as", fpath, r"Merlin KernelV0 (*.akvoK0)")[0]
  396. intDict = dict()
  397. intDict["origin_n"] = self.ui.originN.value()
  398. intDict["origin_e"] = self.ui.originE.value()
  399. intDict["origin_d"] = self.ui.originD.value()
  400. intDict["size_n"] = self.ui.sizeN.value()
  401. intDict["size_e"] = self.ui.sizeE.value()
  402. intDict["size_d"] = self.ui.sizeD.value()
  403. intDict["nLay"] = self.ui.NLayers.value()
  404. intDict["thick1"] = self.ui.thick1.value()
  405. intDict["thickN"] = self.ui.thickN.value()
  406. intDict["Lspacing"] = self.ui.layerSpacing.currentText()
  407. intDict["minLevel"] = self.ui.minLevel.value()
  408. intDict["maxLevel"] = self.ui.maxLevel.value()
  409. intDict["branchTol"] = self.ui.branchTol.value()
  410. intDict["txCoils"] = txCoils
  411. intDict["rxCoils"] = rxCoils
  412. # conductivity model...
  413. #tops = self.ui.layerTableWidget.col(0)
  414. #print("Tops", tops)
  415. tops = []
  416. itop = 0
  417. while self.ui.layerTableWidget.item(itop, 0).text():
  418. tops.append( float(self.ui.layerTableWidget.item(itop,0).text()) )
  419. itop += 1
  420. bots = []
  421. ibot = 0
  422. while self.ui.layerTableWidget.item(ibot, 1).text():
  423. bots.append( float(self.ui.layerTableWidget.item(ibot, 1).text()) )
  424. ibot += 1
  425. sigs = []
  426. isig = 0
  427. while self.ui.layerTableWidget.item(isig, 2).text():
  428. sigs.append( 1./float(self.ui.layerTableWidget.item(isig, 2).text()) )
  429. isig += 1
  430. intDict["tops"] = tops
  431. intDict["bots"] = bots
  432. intDict["sigs"] = sigs
  433. node = yaml.YAML()
  434. kpo = open( "kparams.yml", 'w' )
  435. node.dump(intDict, kpo)
  436. callBox = callScript( ) #QtWidgets.QDialog()
  437. callBox.ui = Ui_callScript()
  438. callBox.ui.setupUi( callBox )
  439. callBox.setupCB( self.K0akvoDataFile, "kparams.yml", saveStr )
  440. callBox.exec_()
  441. callBox.show()
  442. def loopAdd(self):
  443. #print(self.ui.loopLabel.text())
  444. #print(self.ui.loopGeom.currentText())
  445. #print(self.ui.loopType.currentText())
  446. #print( "label len", len(self.ui.loopLabel.text()) )
  447. if len(self.ui.loopLabel.text().strip()) == 0:
  448. Error = QtWidgets.QMessageBox()
  449. Error.setWindowTitle("Error!")
  450. Error.setText("Loop label cannot be blank or repeated")
  451. Error.setDetailedText("Each loop label must be unique and comprise at least one character. Leading and trailing whitespace will be trimmed.")
  452. Error.exec_()
  453. else:
  454. ### Circular loop
  455. if self.ui.loopGeom.currentText() == "Circular":
  456. dialog = QtWidgets.QDialog()
  457. dialog.ui = Ui_circularLoopAdd()
  458. dialog.ui.setupUi(dialog)
  459. dialog.exec_()
  460. dialog.show()
  461. if dialog.result():
  462. cn = dialog.ui.centreNorth.value()
  463. ce = dialog.ui.centreEast.value()
  464. ht = dialog.ui.loopHeight.value()
  465. rad = dialog.ui.loopRadius.value()
  466. turns = dialog.ui.loopTurns.value()
  467. ns = dialog.ui.segments.value()
  468. cwise = dialog.ui.cwiseBox.currentIndex()
  469. #print("cwise", cwise)
  470. #dip = dialog.ui.dip.value()
  471. #azimuth = dialog.ui.az.value()
  472. self.loops[self.ui.loopLabel.text()] = FDEM1D.PolygonalWireAntenna()
  473. self.loops[self.ui.loopLabel.text()].SetNumberOfPoints( dialog.ui.segments.value() + 1 )
  474. self.loops[self.ui.loopLabel.text()].SetNumberOfTurns( dialog.ui.loopTurns.value() )
  475. points = np.linspace(0, 2*np.pi, dialog.ui.segments.value()+1)
  476. for iseg, ipt in enumerate(points):
  477. if cwise == 0:
  478. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn+rad*np.sin(ipt), ce+rad*np.cos(ipt), ht) )
  479. else:
  480. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn-rad*np.sin(ipt), ce+rad*np.cos(ipt), ht) )
  481. self.loops[self.ui.loopLabel.text()].SetNumberOfFrequencies(1)
  482. self.loops[self.ui.loopLabel.text()].SetCurrent(1.)
  483. if self.ui.loopGeom.currentText() == "figure-8":
  484. dialog = QtWidgets.QDialog()
  485. dialog.ui = Ui_figure8LoopAdd()
  486. dialog.ui.setupUi(dialog)
  487. dialog.exec_()
  488. dialog.show()
  489. if dialog.result():
  490. cn1 = dialog.ui.centreNorth1.value()
  491. ce1 = dialog.ui.centreEast1.value()
  492. cn2 = dialog.ui.centreNorth2.value()
  493. ce2 = dialog.ui.centreEast2.value()
  494. ht = dialog.ui.loopHeight.value()
  495. rad = dialog.ui.loopRadius.value()
  496. turns = dialog.ui.loopTurns.value()
  497. ns = dialog.ui.segments.value()
  498. cwise = dialog.ui.cwiseBox.currentIndex()
  499. self.loops[self.ui.loopLabel.text()] = FDEM1D.PolygonalWireAntenna()
  500. self.loops[self.ui.loopLabel.text()].SetNumberOfPoints( 2*dialog.ui.segments.value() + 1 )
  501. self.loops[self.ui.loopLabel.text()].SetNumberOfTurns( dialog.ui.loopTurns.value() )
  502. # first loop
  503. points = np.linspace(0, 2*np.pi, dialog.ui.segments.value())
  504. ptsL = []
  505. for iseg, ipt in enumerate(points):
  506. ptsL.append( np.array( [cn1+rad*np.sin(ipt), ce1+rad*np.cos(ipt)] ))
  507. lenP = len(points)
  508. # search for closest point, ugly and not efficient, but it's not critical here
  509. closest = 1e8
  510. iclosest = -1
  511. for iseg, ipt in enumerate(points):
  512. p2 = np.array([cn2-rad*np.sin(ipt), ce2-rad*np.cos(ipt)])
  513. for p1 in ptsL:
  514. dist = np.linalg.norm(p1-p2)
  515. if dist < closest:
  516. closest = dist
  517. iclosest = iseg
  518. points = np.concatenate([points[iclosest::],points[0:iclosest]])
  519. point1 = False
  520. for iseg, ipt in enumerate(points):
  521. if cwise == 0:
  522. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn1+rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht) )
  523. if not point1:
  524. point1 = ( cn1+rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht)
  525. else:
  526. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn1-rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht) )
  527. if not point1:
  528. point1 = ( cn1-rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht)
  529. lenP = len(points)
  530. # fill
  531. for iseg, ipt in enumerate(points):
  532. if cwise == 0:
  533. self.loops[self.ui.loopLabel.text()].SetPoint(lenP+iseg, ( cn2-rad*np.cos(ipt), ce2-rad*np.sin(ipt), ht) )
  534. else:
  535. self.loops[self.ui.loopLabel.text()].SetPoint(lenP+iseg, ( cn2+rad*np.cos(ipt), ce2+rad*np.sin(ipt), ht) )
  536. # close loop
  537. self.loops[self.ui.loopLabel.text()].SetPoint(lenP+iseg+1, point1)
  538. self.loops[self.ui.loopLabel.text()].SetNumberOfFrequencies(1)
  539. self.loops[self.ui.loopLabel.text()].SetCurrent(1.)
  540. if self.ui.loopGeom.currentText() == "polygon":
  541. dialog = QtWidgets.QDialog()
  542. dialog.ui = Ui_polygonalLoopAdd()
  543. dialog.ui.setupUi(dialog)
  544. ##########################################################################
  545. # Loop Table
  546. dialog.ui.loopTableWidget.setRowCount(80)
  547. dialog.ui.loopTableWidget.setColumnCount(3)
  548. #dialog.ui.loopTableWidget.horizontalHeader().setSectionResizeMode(0, QtGui.Qt.QHeaderView.Stretch)
  549. dialog.ui.loopTableWidget.setHorizontalHeaderLabels( \
  550. ["Northing [m]","Easting [m]","Height [m]"])
  551. for ir in range(0, dialog.ui.loopTableWidget.rowCount() ):
  552. for ic in range(0, 3): #dialog.ui.loopTableWidget.columnCount() ):
  553. pCell = QtWidgets.QTableWidgetItem()
  554. #pCell.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
  555. #pCell.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  556. #pCell.setBackground( QtGui.QColor("lightgrey").lighter(110) )
  557. dialog.ui.loopTableWidget.setItem(ir, ic, pCell)
  558. #dialog.ui.loopTableWidget.cellChanged.connect(self.loopCellChanged)
  559. #dialog.ui.loopTableWidget.itemClicked.connect(self.loopCellClicked)
  560. #self.ui.loopTableWidget.cellPressed.connect(self.loopCellChanged)
  561. #self.ui.loopTableWidget.cellPressed.connect(self.loopCellClicked)
  562. dialog.ui.loopTableWidget.setDragDropOverwriteMode(False)
  563. dialog.ui.loopTableWidget.setDragEnabled(False)
  564. #self.ui.loopTableWidget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  565. dialog.ui.loopTableWidget.resizeColumnsToContents()
  566. dialog.exec_()
  567. dialog.show()
  568. if dialog.result():
  569. self.loops[self.ui.loopLabel.text()] = FDEM1D.PolygonalWireAntenna()
  570. self.loops[self.ui.loopLabel.text()].SetNumberOfTurns( dialog.ui.loopTurns.value() )
  571. npts = 0
  572. for ir in range(0, dialog.ui.loopTableWidget.rowCount() ):
  573. if len(dialog.ui.loopTableWidget.item(ir, 0).text()) == 0:
  574. break
  575. npts += 1
  576. self.loops[self.ui.loopLabel.text()].SetNumberOfPoints( npts )
  577. for ir in range( 0, npts ):
  578. self.loops[self.ui.loopLabel.text()].SetPoint(ir, eval(dialog.ui.loopTableWidget.item(ir, 0).text()), \
  579. eval(dialog.ui.loopTableWidget.item(ir, 1).text()), \
  580. eval(dialog.ui.loopTableWidget.item(ir, 2).text()) \
  581. )
  582. self.loops[self.ui.loopLabel.text()].SetNumberOfFrequencies(1)
  583. self.loops[self.ui.loopLabel.text()].SetCurrent(1.)
  584. # general across all types
  585. if dialog.result():
  586. yml = open( self.ui.loopLabel.text() + ".pwa", 'w' )
  587. print( self.loops[self.ui.loopLabel.text()], file=yml)
  588. # update the table
  589. self.ui.txRxTable.setRowCount( len(self.loops.keys()) )
  590. pCell = QtWidgets.QTableWidgetItem()
  591. pCell.setText( self.ui.loopLabel.text() )
  592. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
  593. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 0, pCell)
  594. gCell = QtWidgets.QTableWidgetItem()
  595. gCell.setText( self.ui.loopGeom.currentText() )
  596. gCell.setFlags( QtCore.Qt.ItemIsEnabled )
  597. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 1, gCell)
  598. tCell = QtWidgets.QTableWidgetItem()
  599. tCell.setText( str(dialog.ui.loopTurns.value()) )
  600. tCell.setFlags( QtCore.Qt.ItemIsEnabled )
  601. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 2, tCell)
  602. txCell = QtWidgets.QTableWidgetItem()
  603. txCell.setText( str(self.ui.loopType.currentText()) )
  604. txCell.setFlags( QtCore.Qt.ItemIsEnabled )
  605. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 3, txCell)
  606. def headerBoxShrink(self):
  607. #self.ui.headerFileBox.setVisible(False)
  608. if self.ui.headerFileBox.isChecked( ):
  609. #self.ui.headerFileBox.setMinimumSize(460,250)
  610. self.ui.headerBox2.setVisible(True)
  611. else:
  612. #self.ui.headerFileBox.setMinimumSize(460,50)
  613. self.ui.headerBox2.setVisible(False)
  614. def sigmaCellChanged(self):
  615. self.ui.layerTableWidget.cellChanged.disconnect(self.sigmaCellChanged)
  616. # TODO consider building the model whenever this is called. Would be nice to be able to
  617. # do that. Would require instead dist of T2 I guess.
  618. jj = self.ui.layerTableWidget.currentColumn()
  619. ii = self.ui.layerTableWidget.currentRow()
  620. val = "class 'NoneType'>"
  621. try:
  622. val = eval (str( self.ui.layerTableWidget.item(ii, jj).text() ))
  623. except:
  624. #if jj != 0:
  625. # Error = QtWidgets.QMessageBox()
  626. # Error.setWindowTitle("Error!")
  627. # Error.setText("Non-numeric value encountered")
  628. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  629. return
  630. if jj == 1:
  631. #item.setFlags(QtCore.Qt.ItemIsEnabled)
  632. pCell = self.ui.layerTableWidget.item(ii, jj)
  633. pCell.setBackground( QtGui.QColor("white"))
  634. pCell = self.ui.layerTableWidget.item(ii+1, jj-1)
  635. if str(type(pCell)) == "<class 'NoneType'>":
  636. pCell = QtWidgets.QTableWidgetItem()
  637. pCell.setFlags(QtCore.Qt.ItemIsEnabled)
  638. self.ui.layerTableWidget.setItem(ii+1, jj-1, pCell)
  639. if ii == 0:
  640. pCell.setText(str(val))
  641. #pCell3 = self.ui.layerTableWidget.item(ii+1, jj)
  642. #print ("setting", ii, jj, type(pCell3))
  643. #print ( "setting", ii, jj, type(pCell3))
  644. #pCell3.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  645. #pCell3.setFlags( QtCore.Qt.ItemIsEditable )
  646. elif ii > 0:
  647. val2 = eval (str( self.ui.layerTableWidget.item(ii-1, jj).text() ))
  648. #print ("val2", val2, val, type(val))
  649. #if str(type(pCell)) == "<class 'NoneType'>":
  650. if type(val) == str or val > val2:
  651. pCell.setText(str(val))
  652. else:
  653. Error = QtWidgets.QMessageBox()
  654. Error.setWindowTitle("Error!")
  655. Error.setText("Non-increasing layer detected")
  656. Error.setDetailedText("Each layer interface must be below the one above it.")
  657. Error.exec_()
  658. #err_msg = "Quadrature detection has already been done!"
  659. #reply =QtWidgets.QMessageBox.critical(self, 'Error',
  660. # err_msg)
  661. pCell2 = self.ui.layerTableWidget.item(ii, jj)
  662. pCell2.setText(str(""))
  663. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  664. return
  665. # enable next layer
  666. pCell4 = self.ui.layerTableWidget.item(ii+1, jj)
  667. pCell4.setBackground( QtGui.QColor("lightblue") ) #.lighter(110))
  668. pCell4.setForeground( QtGui.QColor("black"))
  669. pCell4.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  670. pCell5 = self.ui.layerTableWidget.item(ii+1, jj+1)
  671. pCell5.setBackground( QtGui.QColor("white"))
  672. pCell5.setForeground( QtGui.QColor("black"))
  673. pCell5.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  674. if ii == 0 and jj == 0:
  675. pCell = self.ui.layerTableWidget.item(0, 1)
  676. pCell.setBackground(QtGui.QColor("lightblue")) #.lighter(110) )
  677. pCell.setForeground( QtGui.QColor("black"))
  678. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  679. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  680. def plotLoops2(self):
  681. self.ui.mplwidget.reAxH(1)
  682. for loop in self.loops:
  683. POINTS = self.loops[loop].GetPoints().T
  684. self.ui.mplwidget.ax1.plot( POINTS[:,1], POINTS[:,0], label=loop )
  685. self.ui.mplwidget.ax1.spines['right'].set_visible(False)
  686. self.ui.mplwidget.ax1.spines['top'].set_visible(False)
  687. self.ui.mplwidget.ax1.set_xlabel("easting (m)")
  688. self.ui.mplwidget.ax1.set_ylabel("northing (m)")
  689. self.ui.mplwidget.ax1.legend()
  690. self.ui.mplwidget.ax1.set_aspect('equal') #, adjustable='box')
  691. self.ui.mplwidget.draw()
  692. def removeLoop(self):
  693. del self.loops[ self.ui.txRxTable.item( self.ui.txRxTable.currentRow(), 0).text() ]
  694. self.ui.txRxTable.removeRow(self.ui.txRxTable.currentRow())
  695. def about(self):
  696. # TODO proper popup with info
  697. #self.w = MyPopup("""About Akvo \n
  698. # Akvo is an open source project developed primarily by Trevor Irons.
  699. #""")
  700. #self.w.setGeometry(100, 100, 400, 200)
  701. #self.w.show()
  702. #print("ABOUT")
  703. # Just a splash screen for now
  704. logo = pkg_resources.resource_filename(__name__, 'akvo-about.png')
  705. pixmap = QtGui.QPixmap(logo)
  706. self.splash = QtWidgets.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
  707. self.splash.show()
  708. def connectGMRDataProcessor(self):
  709. self.RAWDataProc = mrsurvey.GMRDataProcessor()
  710. self.RAWDataProc.progressTrigger.connect(self.updateProgressBar)
  711. self.RAWDataProc.enableDSPTrigger.connect(self.enableDSP)
  712. self.RAWDataProc.doneTrigger.connect(self.doneStatus)
  713. self.RAWDataProc.updateProcTrigger.connect(self.updateProc)
  714. def openGMRRAWDataset(self):
  715. """ Opens a GMR header file
  716. """
  717. try:
  718. with open('.gmr.last.path') as f:
  719. fpath = f.readline()
  720. pass
  721. except IOError as e:
  722. fpath = '.'
  723. self.headerstr = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', fpath)[0] # arg2 = File Type 'All Files (*)'
  724. self.ui.headerFileTextBrowser.clear()
  725. self.ui.headerFileTextBrowser.append(self.headerstr)
  726. if len(self.headerstr) == 0:
  727. return
  728. # clear the processing log
  729. self.ui.logTextBrowser.clear()
  730. self.logText = [] #MAK 20170126
  731. path,filen=os.path.split(str(self.headerstr))
  732. f = open('.gmr.last.path', 'w')
  733. f.write( str(self.headerstr) ) # prompt last file
  734. self.connectGMRDataProcessor()
  735. self.RAWDataProc.readHeaderFile(str(self.headerstr))
  736. # If we got this far, enable all the widgets
  737. self.ui.lcdNumberTauPulse1.setEnabled(True)
  738. self.ui.lcdNumberNuTx.setEnabled(True)
  739. self.ui.lcdNumberTuneuF.setEnabled(True)
  740. self.ui.lcdNumberSampFreq.setEnabled(True)
  741. self.ui.lcdNumberNQ.setEnabled(True)
  742. self.ui.headerFileBox.setEnabled(True)
  743. self.ui.headerFileBox.setChecked( True )
  744. self.ui.headerBox2.setVisible(True)
  745. self.ui.inputRAWParametersBox.setEnabled(True)
  746. self.ui.loadDataPushButton.setEnabled(True)
  747. # make plots as you import the dataset
  748. self.ui.plotImportCheckBox.setEnabled(True)
  749. self.ui.plotImportCheckBox.setChecked(True)
  750. # Update info from the header into the GUI
  751. self.ui.pulseTypeTextBrowser.clear()
  752. self.ui.pulseTypeTextBrowser.append(self.RAWDataProc.pulseType)
  753. self.ui.lcdNumberNuTx.display(self.RAWDataProc.transFreq)
  754. self.ui.lcdNumberTauPulse1.display(1e3*self.RAWDataProc.pulseLength[0])
  755. self.ui.lcdNumberTuneuF.display(self.RAWDataProc.TuneCapacitance)
  756. self.ui.lcdNumberSampFreq.display(self.RAWDataProc.samp)
  757. self.ui.lcdNumberNQ.display(self.RAWDataProc.nPulseMoments)
  758. self.ui.DeadTimeSpinBox.setValue(1e3*self.RAWDataProc.deadTime)
  759. self.ui.CentralVSpinBox.setValue( self.RAWDataProc.transFreq )
  760. # set the B0 field according to Tx as an initial guess
  761. self.ui.intensitySpinBox.setValue( self.RAWDataProc.transFreq/GAMMAH )
  762. if self.RAWDataProc.pulseType != "FID":
  763. self.ui.lcdNumberTauPulse2.setEnabled(1)
  764. self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  765. self.ui.lcdNumberTauDelay.setEnabled(1)
  766. self.ui.lcdNumberTauDelay.display(1e3*self.RAWDataProc.interpulseDelay)
  767. self.ui.FIDProcComboBox.clear()
  768. if self.RAWDataProc.pulseType == "4PhaseT1" or self.RAWDataProc.pulseType == "T1":
  769. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1")
  770. self.ui.FIDProcComboBox.insertItem(1, "Pulse 2")
  771. self.ui.FIDProcComboBox.insertItem(2, "Both")
  772. self.ui.FIDProcComboBox.setCurrentIndex (1)
  773. elif self.RAWDataProc.pulseType == "FID":
  774. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1")
  775. self.ui.FIDProcComboBox.setCurrentIndex (0)
  776. def ExportPreprocess(self):
  777. """ This method exports to YAML
  778. """
  779. try:
  780. with open('.akvo.last.yaml.path') as f:
  781. fpath = f.readline()
  782. pass
  783. except IOError as e:
  784. fpath = '.'
  785. fdir = os.path.dirname(fpath)
  786. # Pickle the preprocessed data dictionary
  787. SaveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save as", fdir, r"Processed data (*.akvoProcData)")[0]
  788. spath,filen=os.path.split(str(SaveStr))
  789. f = open('.akvo.last.yaml.path', 'w')
  790. f.write( str(spath) ) # prompt last file
  791. INFO = {}
  792. INFO["headerstr"] = str(self.headerstr)
  793. INFO["pulseType"] = self.RAWDataProc.pulseType
  794. INFO["transFreq"] = self.RAWDataProc.transFreq.tolist()
  795. INFO["pulseLength"] = self.RAWDataProc.pulseLength.tolist()
  796. INFO["TuneCapacitance"] = self.RAWDataProc.TuneCapacitance.tolist()
  797. #INFO["samp"] = self.RAWDataProc.samp
  798. INFO["nPulseMoments"] = self.RAWDataProc.nPulseMoments
  799. #INFO["deadTime"] = self.RAWDataProc.deadTime
  800. INFO["processed"] = "Akvo v" + VERSION + ", on " + time.strftime("%d/%m/%Y")
  801. # Pulse current info
  802. ip = 0
  803. INFO["Pulses"] = {}
  804. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  805. qq = []
  806. qv = []
  807. for ipm in range(self.RAWDataProc.DATADICT["nPulseMoments"]):
  808. #for istack in self.RAWDataProc.DATADICT["stacks"]:
  809. # print ("stack q", self.RAWDataProc.DATADICT[pulse]["Q"][ipm,istack-1])
  810. qq.append(np.mean( self.RAWDataProc.DATADICT[pulse]["Q"][ipm,:]) )
  811. qv.append(np.std( self.RAWDataProc.DATADICT[pulse]["Q"][ipm,:]/self.RAWDataProc.pulseLength[ip] ))
  812. qq = np.array(qq)
  813. qv = np.array(qv)
  814. iQ = np.argsort(np.array(qq))
  815. qq = np.array(qq)[iQ]
  816. qv = np.array(qv)[iQ]
  817. INFO["Pulses"][pulse] = {}
  818. INFO["Pulses"][pulse]["units"] = "A"
  819. INFO["Pulses"][pulse]["current"] = VectorXr(qq/self.RAWDataProc.pulseLength[ip])
  820. INFO["Pulses"][pulse]["variance"] = VectorXr(qv)
  821. ip += 1
  822. # Data
  823. if self.RAWDataProc.gated == True:
  824. INFO["Gated"] = {}
  825. INFO["Gated"]["abscissa units"] = "ms"
  826. INFO["Gated"]["data units"] = "nT"
  827. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  828. INFO["Gated"][pulse] = {}
  829. INFO["Gated"][pulse]["abscissa"] = VectorXr( self.RAWDataProc.GATEDABSCISSA )
  830. INFO["Gated"][pulse]["windows"] = VectorXr( self.RAWDataProc.GATEDWINDOW )
  831. for ichan in self.RAWDataProc.DATADICT[pulse]["chan"]:
  832. INFO["Gated"][pulse]["Chan. " + str(ichan)] = {}
  833. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["STD"] = VectorXr( np.std(self.RAWDataProc.GATED[ichan]["NR"], axis=0) )
  834. INFO["Gated"][pulse]["Chan. " + str(ichan)]["STD"] = VectorXr( np.average(self.RAWDataProc.GATED[ichan]["BN"], axis=0) )
  835. for ipm in range(self.RAWDataProc.DATADICT["nPulseMoments"]):
  836. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " CA"] = VectorXr(self.RAWDataProc.GATED[ichan]["CA"][ipm])
  837. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " RE"] = VectorXr(self.RAWDataProc.GATED[ichan]["RE"][ipm])
  838. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " IM"] = VectorXr(self.RAWDataProc.GATED[ichan]["IM"][ipm])
  839. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " IP"] = VectorXr(self.RAWDataProc.GATED[ichan]["IP"][ipm])
  840. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " NR"] = VectorXr(self.RAWDataProc.GATED[ichan]["NR"][ipm])
  841. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " STD" ] = VectorXr(self.RAWDataProc.GATED[ichan]["SIGMA"][ipm])
  842. # we have gated data
  843. # Window edges
  844. # Window centres
  845. with open(SaveStr, 'w') as outfile:
  846. #for line in self.logText:
  847. # outfile.write(line+"\n")
  848. yaml.dump(self.YamlNode, outfile)
  849. yaml.dump(INFO, outfile) #, default_flow_style=False)
  850. def SavePreprocess(self):
  851. #if "Saved" not in self.YamlNode.Processing.keys():
  852. # self.YamlNode.Processing["Saved"] = []
  853. #self.YamlNode.Processing["Saved"].append(datetime.datetime.now().isoformat())
  854. #self.Log()
  855. import pickle, os
  856. try:
  857. with open('.akvo.last.path') as f:
  858. fpath = f.readline()
  859. pass
  860. except IOError as e:
  861. fpath = '.'
  862. fdir = os.path.dirname(fpath)
  863. # Pickle the preprocessed data dictionary
  864. SaveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save as", fdir, r"Pickle (*.dmp)")
  865. spath,filen=os.path.split(str(SaveStr[0]))
  866. f = open('.akvo.last.path', 'w')
  867. f.write( str(spath) ) # prompt last file
  868. save = open(SaveStr[0], 'wb')
  869. # Add some extra info
  870. INFO = {}
  871. INFO["pulseType"] = self.RAWDataProc.pulseType
  872. INFO["prePulseDelay"] = self.RAWDataProc.prePulseDelay
  873. INFO["interpulseDelay"] = self.RAWDataProc.interpulseDelay
  874. INFO["transFreq"] = self.RAWDataProc.transFreq
  875. INFO["pulseLength"] = self.RAWDataProc.pulseLength
  876. INFO["TuneCapacitance"] = self.RAWDataProc.TuneCapacitance
  877. INFO["samp"] = self.RAWDataProc.samp
  878. INFO["nPulseMoments"] = self.RAWDataProc.nPulseMoments
  879. INFO["deadTime"] = self.RAWDataProc.deadTime
  880. INFO["transFreq"] = self.RAWDataProc.transFreq
  881. INFO["headerstr"] = str(self.headerstr)
  882. INFO["nDAQVersion"] = self.RAWDataProc.nDAQVersion
  883. INFO["log"] = yaml.dump( self.YamlNode )
  884. TXRX = []
  885. for ir in range(0, self.ui.txRxTable.rowCount() ):
  886. txrx = []
  887. for ic in range(0, self.ui.txRxTable.columnCount() ):
  888. txrx.append( self.ui.txRxTable.item(ir, ic).text() )
  889. TXRX.append(txrx)
  890. INFO["TXRX"] = TXRX
  891. if "Stacking" in self.YamlNode.Stacking.keys():
  892. INFO["sigma"] = self.RawDataProc.sigma
  893. if "Gate integrate" in self.YamlNode.Stacking.keys():
  894. INFO["GATED"] = self.RAWDataProc.GATED
  895. print("META SAVE")
  896. print("INFO log", INFO["log"])
  897. self.RAWDataProc.DATADICT["INFO"] = INFO
  898. pickle.dump(self.RAWDataProc.DATADICT, save)
  899. save.close()
  900. # Export XML file suitable for USGS ScienceBase Data Release
  901. def ExportXML(self):
  902. """ This is a filler function for use by USGS collaborators
  903. """
  904. return 42
  905. def OpenPreprocess(self):
  906. import pickle
  907. try:
  908. with open('.akvo.last.path') as f:
  909. fpath = f.readline()
  910. pass
  911. except IOError as e:
  912. fpath = '.'
  913. #filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', '.')
  914. fpath = QtWidgets.QFileDialog.getOpenFileName(self, 'Open preprocessed file', fpath, r"Pickle Files (*.dmp)")[0]
  915. f = open('.akvo.last.path', 'w')
  916. f.write( str(fpath) ) # prompt last file
  917. self.ui.logTextBrowser.clear()
  918. self.logText = []
  919. if len(fpath) == 0:
  920. return
  921. pfile = open(fpath,'rb')
  922. unpickle = pickle.Unpickler(pfile)
  923. self.connectGMRDataProcessor()
  924. self.RAWDataProc.DATADICT = unpickle.load()
  925. # This line causes Akvo to crash, if the header file is no longer there. We don't need to load the
  926. # file. TODO, need to disable "Load Data" in Load command though, as that is no longer possible.
  927. #self.RAWDataProc.readHeaderFile(self.RAWDataProc.DATADICT["INFO"]["headerstr"])
  928. self.headerstr = self.RAWDataProc.DATADICT["INFO"]["headerstr"]
  929. self.RAWDataProc.pulseType = self.RAWDataProc.DATADICT["INFO"]["pulseType"]
  930. self.RAWDataProc.transFreq = self.RAWDataProc.DATADICT["INFO"]["transFreq"]
  931. self.RAWDataProc.pulseLength = self.RAWDataProc.DATADICT["INFO"]["pulseLength"]
  932. self.RAWDataProc.TuneCapacitance = self.RAWDataProc.DATADICT["INFO"]["TuneCapacitance"]
  933. self.RAWDataProc.samp = self.RAWDataProc.DATADICT["INFO"]["samp"]
  934. self.RAWDataProc.nPulseMoments = self.RAWDataProc.DATADICT["INFO"]["nPulseMoments"]
  935. self.RAWDataProc.deadTime = self.RAWDataProc.DATADICT["INFO"]["deadTime"]
  936. self.RAWDataProc.transFreq = self.RAWDataProc.DATADICT["INFO"]["transFreq"]
  937. self.RAWDataProc.nDAQVersion = self.RAWDataProc.DATADICT["INFO"]["nDAQVersion"]
  938. #self.RAWDataProc.prePulseDelay = self.RAWDataProc.DATADICT["INFO"]["prePulseDelay"]
  939. self.RAWDataProc.dt = 1./self.RAWDataProc.samp
  940. self.dataChan = self.RAWDataProc.DATADICT[ self.RAWDataProc.DATADICT["PULSES"][0] ]["chan"]
  941. # Keep backwards compatibility with prior saved pickles???
  942. #self.ui.logTextBrowser.clear()
  943. #self.ui.logTextBrowser.append( yaml.dump(self.YamlNode)) #, default_flow_style=False) )
  944. #for a in self.logText:
  945. # self.ui.logTextBrowser.append(str(a))
  946. #self.ui.logTextBrowser
  947. #self.ui.logTextBrowser.clear()
  948. #print ( self.RAWDataProc.DATADICT["INFO"]["log"] )
  949. if "TXRX" in self.RAWDataProc.DATADICT["INFO"].keys():
  950. TXRX = self.RAWDataProc.DATADICT["INFO"]["TXRX"]
  951. self.ui.txRxTable.setRowCount( len(TXRX))
  952. for irow, row in enumerate(TXRX):
  953. for icol, val in enumerate(row):
  954. pCell = QtWidgets.QTableWidgetItem()
  955. pCell.setText( val )
  956. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
  957. self.ui.txRxTable.setItem(irow, icol, pCell)
  958. self.logText = self.RAWDataProc.DATADICT["INFO"]["log"] # YAML
  959. parse = yaml.load( self.logText, Loader=yaml.Loader )
  960. self.YamlNode = AkvoYamlNode( ) #self.logText )
  961. self.YamlNode.Akvo_VERSION = (yaml.load( self.logText, Loader=yaml.Loader )).Akvo_VERSION
  962. AKVO_VERSION = np.array(self.YamlNode.Akvo_VERSION.split("."), dtype=int)
  963. if AKVO_VERSION[0] >= 1 and AKVO_VERSION[1] >= 2 and AKVO_VERSION[2] >= 3:
  964. self.RAWDataProc.interpulseDelay = self.RAWDataProc.DATADICT["INFO"]["interpulseDelay"]
  965. self.YamlNode.Import = OrderedDict(parse.Import)
  966. self.YamlNode.Processing = list(parse.Processing)
  967. self.YamlNode.Stacking = OrderedDict(parse.Stacking)
  968. self.YamlNode.META = OrderedDict(parse.META)
  969. self.logGUI()
  970. self.Log()
  971. #self.ui.logTextBrowser.append( yaml.dump(self.YamlNode)) #, default_flow_style=False) )
  972. #except KeyError:
  973. # pass
  974. # Remove "Saved" and "Loaded" from processing flow
  975. #if "Loaded" not in self.YamlNode.Processing.keys():
  976. # self.YamlNode.Processing["Loaded"] = []
  977. #self.YamlNode.Processing["Loaded"].append(datetime.datetime.now().isoformat())
  978. #self.Log()
  979. if "Stacking" in self.YamlNode.Stacking.keys():
  980. self.RAWDataProc.sigma = self.RAWDataProc.DATADICT["sigma"]
  981. # check to see if gate integration has been done, and it's ready to send to Merlin
  982. if "Gate integrate" in self.YamlNode.Stacking.keys():
  983. self.RAWDataProc.GATED = self.RAWDataProc.DATADICT["GATED"]
  984. self.ui.actionExport_Preprocessed_Dataset.setEnabled(True)
  985. #self.ui.plotGI.setEnabled(True)
  986. # If we got this far, enable all the widgets
  987. self.ui.lcdNumberTauPulse1.setEnabled(True)
  988. self.ui.lcdNumberNuTx.setEnabled(True)
  989. self.ui.lcdNumberTuneuF.setEnabled(True)
  990. self.ui.lcdNumberSampFreq.setEnabled(True)
  991. self.ui.lcdNumberNQ.setEnabled(True)
  992. self.ui.headerFileBox.setEnabled(True)
  993. self.ui.headerFileBox.setChecked( True )
  994. self.headerBoxShrink()
  995. #self.ui.headerBox2.setVisible(True)
  996. self.ui.inputRAWParametersBox.setEnabled(False)
  997. self.ui.loadDataPushButton.setEnabled(True)
  998. # make plots as you import the datasetmost
  999. self.ui.plotImportCheckBox.setEnabled(True)
  1000. self.ui.plotImportCheckBox.setChecked(True)
  1001. # enable the LCDs
  1002. self.ui.lcdNumberFID1Length.setEnabled(1)
  1003. self.ui.lcdNumberFID2Length.setEnabled(1)
  1004. self.ui.lcdNumberResampFreq.setEnabled(1)
  1005. self.ui.lcdTotalDeadTime.setEnabled(1)
  1006. # enable META tab
  1007. self.ui.METATab.setEnabled(1)
  1008. self.ui.siteBox.setEnabled(1)
  1009. #self.ui.lcdTotalDeadTime.display( 1e3*self.RAWDataProc.DATADICT["INFO"]["deadTime"] )
  1010. self.ui.headerFileTextBrowser.clear( )
  1011. self.ui.headerFileTextBrowser.append( self.RAWDataProc.DATADICT["INFO"]["headerstr"] )
  1012. if u"Pulse 1" in self.RAWDataProc.DATADICT.keys():
  1013. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1014. self.ui.lcdTotalDeadTime.display( round(1e3*(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 1"]["PULSE_TIMES"][-1]), 3) )
  1015. #print("CALC DEAD", (1e3*(self.RAWDataProc.prePulseDelay))) # - (self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 1"]["PULSE_TIMES"][-1])), 3) )
  1016. if u"Pulse 2" in self.RAWDataProc.DATADICT.keys():
  1017. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1018. self.ui.lcdTotalDeadTime.display( 1e3 * (self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 2"]["PULSE_TIMES"][-1]) )
  1019. # Update info from the header into the GUI
  1020. self.ui.pulseTypeTextBrowser.clear()
  1021. self.ui.pulseTypeTextBrowser.append(self.RAWDataProc.pulseType)
  1022. self.ui.lcdNumberNuTx.display(self.RAWDataProc.transFreq)
  1023. self.ui.lcdNumberTauPulse1.display(1e3*self.RAWDataProc.pulseLength[0])
  1024. self.ui.lcdNumberTuneuF.display(self.RAWDataProc.TuneCapacitance)
  1025. self.ui.lcdNumberResampFreq.display(self.RAWDataProc.samp)
  1026. self.ui.lcdNumberSampFreq.display(50000) # TODO, if non GMR is supported, query
  1027. self.ui.lcdNumberNQ.display(self.RAWDataProc.nPulseMoments)
  1028. self.ui.DeadTimeSpinBox.setValue(1e3*self.RAWDataProc.deadTime)
  1029. self.ui.CentralVSpinBox.setValue( self.RAWDataProc.transFreq )
  1030. if self.RAWDataProc.pulseType != "FID":
  1031. self.ui.lcdNumberTauPulse2.setEnabled(1)
  1032. self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  1033. self.ui.lcdNumberTauDelay.setEnabled(1)
  1034. self.ui.lcdNumberTauDelay.display(1e3*self.RAWDataProc.interpulseDelay)
  1035. self.ui.FIDProcComboBox.clear()
  1036. if self.RAWDataProc.pulseType == "4PhaseT1" or self.RAWDataProc.pulseType == "T1":
  1037. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  1038. self.ui.FIDProcComboBox.insertItem(1, "Pulse 2") #, const QVariant & userData = QVariant() )
  1039. self.ui.FIDProcComboBox.insertItem(2, "Both") #, const QVariant & userData = QVariant() )
  1040. if len( self.RAWDataProc.DATADICT["PULSES"]) == 2:
  1041. self.ui.FIDProcComboBox.setCurrentIndex (2)
  1042. elif self.RAWDataProc.DATADICT["PULSES"][0] == "Pulse 1":
  1043. self.ui.FIDProcComboBox.setCurrentIndex (0)
  1044. else:
  1045. self.ui.FIDProcComboBox.setCurrentIndex (1)
  1046. elif self.RAWDataProc.pulseType == "FID":
  1047. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  1048. self.ui.FIDProcComboBox.setCurrentIndex (0)
  1049. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  1050. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  1051. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  1052. self.RAWDataProc.progressTrigger.connect(self.updateProgressBar)
  1053. self.RAWDataProc.enableDSPTrigger.connect(self.enableDSP)
  1054. self.RAWDataProc.doneTrigger.connect(self.doneStatus)
  1055. self.enableAll()
  1056. def loadRAW(self):
  1057. #################################################
  1058. # Check to make sure we are ready to process
  1059. # Header
  1060. if self.RAWDataProc == None:
  1061. err_msg = "You need to load a header first."
  1062. reply = QtGui.QMessageBox.critical(self, 'Error',
  1063. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  1064. return
  1065. # Stacks
  1066. try:
  1067. self.procStacks = np.array(eval(str("np.r_["+self.ui.stacksLineEdit.text())+"]"))
  1068. except:
  1069. err_msg = "You need to set your stacks correctly.\n" + \
  1070. "This should be a Python Numpy interpretable list\n" + \
  1071. "of stack indices. For example 1:24 or 1:4,8:24"
  1072. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  1073. return
  1074. # Data Channels
  1075. #Chan = np.arange(0,9,1)
  1076. try:
  1077. self.dataChan = np.array(eval(str("np.r_["+self.ui.dataChanLineEdit.text())+"]"))
  1078. except:
  1079. #QMessageBox messageBox;
  1080. #messageBox.critical(0,"Error","An error has occured !");
  1081. #messageBox.setFixedSize(500,200);
  1082. #quit_msg = "Are you sure you want to exit the program?"
  1083. #reply = QtGui.QMessageBox.question(self, 'Message',
  1084. # quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  1085. err_msg = "You need to set your data channels correctly.\n" + \
  1086. "This should be a Python Numpy interpretable list\n" + \
  1087. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  1088. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  1089. "1:3 is not inclusive of 3 and is the same as 1,2 "
  1090. reply = QtGui.QMessageBox.critical(self, 'Error',
  1091. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  1092. return
  1093. #############################
  1094. # Reference Channels
  1095. # TODO make sure no overlap between data and ref channels
  1096. self.refChan = np.array( () )
  1097. if str(self.ui.refChanLineEdit.text()): # != "none":
  1098. try:
  1099. self.refChan = np.array(eval(str("np.r_["+self.ui.refChanLineEdit.text())+"]"))
  1100. except:
  1101. err_msg = "You need to set your reference channels correctly.\n" + \
  1102. "This should be a Python Numpy interpretable list\n" + \
  1103. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  1104. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  1105. "1:3 is not inclusive of 3 and is the same as 1,2 "
  1106. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  1107. return
  1108. #####################################################
  1109. # Load data
  1110. self.lock("loading RAW GMR dataset")
  1111. if self.RAWDataProc.pulseType == "FID":
  1112. self.procThread = thread.start_new_thread(self.RAWDataProc.loadFIDData, \
  1113. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1114. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1115. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1116. elif self.RAWDataProc.pulseType == "4PhaseT1":
  1117. self.procThread = thread.start_new_thread(self.RAWDataProc.load4PhaseT1Data, \
  1118. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1119. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1120. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1121. elif self.RAWDataProc.pulseType == "T1":
  1122. self.procThread = thread.start_new_thread(self.RAWDataProc.loadT1Data, \
  1123. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1124. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1125. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1126. #self.procThread = thread.start_new_thread(self.RAWDataProc.load4PhaseT1Data, \
  1127. # (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1128. # str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1129. # 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1130. self.YamlNode.Import["GMR Header"] = self.headerstr
  1131. self.YamlNode.Import["opened"] = datetime.datetime.now().isoformat()
  1132. self.YamlNode.Import["pulse Type"] = str(self.RAWDataProc.pulseType)
  1133. self.YamlNode.Import["stacks"] = self.procStacks.tolist()
  1134. self.YamlNode.Import["data channels"] = self.dataChan.tolist()
  1135. self.YamlNode.Import["reference channels"] = self.refChan.tolist()
  1136. self.YamlNode.Import["pulse records"] = str(self.ui.FIDProcComboBox.currentText())
  1137. self.YamlNode.Import["instrument dead time"] = (1e-3 * self.ui.DeadTimeSpinBox.value( ))
  1138. self.Log ( )
  1139. # enable META tab
  1140. self.ui.METATab.setEnabled(1)
  1141. self.ui.siteBox.setEnabled(1)
  1142. # should be already done
  1143. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  1144. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  1145. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  1146. #self.ui.ProcessedBox.setEnabled(True)
  1147. self.ui.lcdNumberFID1Length.setEnabled(1)
  1148. self.ui.lcdNumberFID2Length.setEnabled(1)
  1149. self.ui.lcdNumberResampFreq.setEnabled(1)
  1150. self.ui.lcdTotalDeadTime.setEnabled(1)
  1151. self.ui.lcdTotalDeadTime.display( self.ui.DeadTimeSpinBox.value( ) )
  1152. #self.ui.lcdTotalDeadTime.display( round(1e3*(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 1"]["PULSE_TIMES"][-1]), 3) )
  1153. #self.ui.lcdNumberFID1Length.display(0)
  1154. #self.ui.lcdNumberFID2Length.display(0)
  1155. #self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  1156. self.mpl_toolbar = NavigationToolbar2QT(self.ui.mplwidget, self.ui.mplwidget)
  1157. self.ui.mplwidget.draw()
  1158. def Log(self):
  1159. #for line in yaml.dump(self.YamlNode, default_flow_style=False):
  1160. #for line in nlogText:
  1161. # self.ui.logTextBrowser.append( line )
  1162. # self.logText.append( line )
  1163. self.ui.logTextBrowser.clear()
  1164. self.ui.logTextBrowser.append( yaml.dump(self.YamlNode ))
  1165. def disable(self):
  1166. self.ui.inputRAWParametersBox.setEnabled(False)
  1167. self.ui.BandPassBox.setEnabled(False)
  1168. self.ui.downSampleGroupBox.setEnabled(False)
  1169. self.ui.windowFilterGroupBox.setEnabled(False)
  1170. self.ui.harmonicBox.setEnabled(False)
  1171. # self.ui.despikeGroupBox.setEnabled(False)
  1172. self.ui.adaptBox.setEnabled(False)
  1173. self.ui.adaptFDBox.setEnabled(False)
  1174. self.ui.qCalcGroupBox.setEnabled(False)
  1175. self.ui.FDSmartStackGroupBox.setEnabled(False)
  1176. self.ui.sumDataBox.setEnabled(False)
  1177. self.ui.qdGroupBox.setEnabled(False)
  1178. self.ui.gateBox.setEnabled(False)
  1179. def enableAll(self):
  1180. self.enableDSP()
  1181. self.enableQC()
  1182. def enableDSP(self):
  1183. # Bandpass filter
  1184. self.ui.BandPassBox.setEnabled(True)
  1185. self.ui.BandPassBox.setChecked(True)
  1186. self.ui.bandPassGO.setEnabled(False) # need to design first
  1187. self.ui.plotBP.setEnabled(True)
  1188. self.ui.plotBP.setChecked(True)
  1189. # downsample
  1190. self.ui.downSampleGroupBox.setEnabled(True)
  1191. self.ui.downSampleGroupBox.setChecked(True)
  1192. # window
  1193. self.ui.windowFilterGroupBox.setEnabled(True)
  1194. self.ui.windowFilterGroupBox.setChecked(True)
  1195. # Despike
  1196. # self.ui.despikeGroupBox.setEnabled(True)
  1197. # self.ui.despikeGroupBox.setChecked(False)
  1198. # Adaptive filtering
  1199. self.ui.adaptBox.setEnabled(True)
  1200. self.ui.adaptBox.setChecked(True)
  1201. # FD Adaptive filtering
  1202. self.ui.adaptFDBox.setEnabled(True)
  1203. self.ui.adaptFDBox.setChecked(False)
  1204. # Harmonic
  1205. self.ui.harmonicBox.setEnabled(True)
  1206. self.ui.harmonicBox.setChecked(True)
  1207. self.LCDHarmonics()
  1208. self.LCDHarmonics2()
  1209. # sum group box
  1210. try:
  1211. if len(self.dataChan) > 1:
  1212. self.ui.sumDataBox.setEnabled(True)
  1213. self.ui.sumDataBox.setChecked(False)
  1214. except:
  1215. pass
  1216. # Quadrature Detect
  1217. self.ui.qdGroupBox.setEnabled(True)
  1218. self.ui.qdGroupBox.setChecked(True)
  1219. self.enableQC()
  1220. def enableQC(self):
  1221. # Q calc
  1222. self.ui.qCalcGroupBox.setEnabled(True)
  1223. self.ui.qCalcGroupBox.setChecked(True)
  1224. # FD SmartStack
  1225. self.ui.FDSmartStackGroupBox.setEnabled(True)
  1226. self.ui.FDSmartStackGroupBox.setChecked(True)
  1227. # Quadrature detect
  1228. try:
  1229. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  1230. np.shape(self.RAWDataProc.DATADICT[pulse]["Q"])
  1231. self.RAWDataProc.DATADICT["stack"]
  1232. self.ui.qdGroupBox.setEnabled(True)
  1233. self.ui.qdGroupBox.setChecked(True)
  1234. except:
  1235. self.ui.qdGroupBox.setEnabled(False)
  1236. self.ui.qdGroupBox.setChecked(False)
  1237. # Gating
  1238. try:
  1239. self.RAWDataProc.DATADICT["CA"]
  1240. self.ui.gateBox.setEnabled(True)
  1241. self.ui.gateBox.setChecked(True)
  1242. except:
  1243. self.ui.gateBox.setEnabled(False)
  1244. self.ui.gateBox.setChecked(False)
  1245. def despikeFilter(self):
  1246. self.lock("despike filter")
  1247. thread.start_new_thread(self.RAWDataProc.despike, \
  1248. (self.ui.windowSpinBox.value(), \
  1249. self.ui.thresholdSpinBox.value(), \
  1250. str(self.ui.replComboBox.currentText()), \
  1251. self.ui.rollOnSpinBox.value(), \
  1252. self.ui.despikeInterpWinSpinBox.value(),
  1253. self.ui.mplwidget))
  1254. def calcQ(self):
  1255. if "Calc Q" not in self.YamlNode.Stacking.keys():
  1256. #print("In CalcQ", yaml.dump(self.YamlNode.Processing) )
  1257. self.YamlNode.Stacking["Calc Q"] = True
  1258. #print( yaml.dump(self.YamlNode.Processing) )
  1259. self.Log()
  1260. else:
  1261. err_msg = "Q values have already been calculated"
  1262. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1263. err_msg)
  1264. return
  1265. self.lock("pulse moment calculation")
  1266. thread.start_new_thread(self.RAWDataProc.effectivePulseMoment, \
  1267. (self.ui.CentralVSpinBox.value(), \
  1268. self.ui.mplwidget))
  1269. def harmonicModel(self):
  1270. self.lock("harmonic noise modelling")
  1271. Harm = OrderedDict()
  1272. Harm["STEP " + str(len(self.YamlNode.Processing))] = "Harmonic modelling"
  1273. Harm["NF"] = str( self.ui.NHarmonicsFreqsSpin.value() )
  1274. Harm["Segments"] = str( self.ui.NSegments.value() )
  1275. Harm["Proc. ref."] = self.ui.harmRef.isChecked()
  1276. if self.ui.searchAll.currentText() == "All":
  1277. Harm["search"] = self.ui.searchAll.currentText()
  1278. Search = False
  1279. else:
  1280. #Harm["search"] = self.ui.searchAll.currentText()
  1281. Harm["search"] = str(self.ui.Nsearch.value())
  1282. Search = self.ui.Nsearch.value()
  1283. if self.ui.boundsCheck.isChecked():
  1284. Harm["Bounds"] = str(self.ui.bounds.value())
  1285. Bounds = self.ui.bounds.value()
  1286. else:
  1287. Harm["Bounds"] = self.ui.boundsCheck.isChecked()
  1288. Bounds = 0
  1289. Harm["f0K1"] = str( self.ui.f0K1Spin.value() )
  1290. Harm["f0KN"] = str( self.ui.f0KNSpin.value() )
  1291. Harm["f0Ks"] = str( self.ui.f0KsSpin.value() )
  1292. Harm["f0"] = str( self.ui.f0Spin.value() )
  1293. if self.ui.NHarmonicsFreqsSpin.value() > 1:
  1294. Harm["f1K1"] = str( self.ui.f1K1Spin.value() )
  1295. Harm["f1KN"] = str( self.ui.f1KNSpin.value() )
  1296. Harm["f1Ks"] = str( self.ui.f1KsSpin.value() )
  1297. Harm["f1"] = str( self.ui.f1Spin.value() )
  1298. self.YamlNode.Processing.append(Harm)
  1299. self.Log()
  1300. thread.start_new_thread(self.RAWDataProc.harmonicModel, \
  1301. ( \
  1302. self.ui.NHarmonicsFreqsSpin.value(), \
  1303. self.ui.f0Spin.value(), \
  1304. self.ui.f0K1Spin.value(), \
  1305. self.ui.f0KNSpin.value(), \
  1306. self.ui.f0KsSpin.value(), \
  1307. self.ui.NSegments.value(), \
  1308. self.ui.f1Spin.value(), \
  1309. self.ui.f1K1Spin.value(), \
  1310. self.ui.f1KNSpin.value(), \
  1311. self.ui.f1KsSpin.value(), \
  1312. Search, \
  1313. Bounds, \
  1314. self.ui.harmRef.isChecked(), \
  1315. self.ui.plotHarmonic.isChecked(), \
  1316. self.ui.mplwidget \
  1317. ) \
  1318. )
  1319. def FDSmartStack(self):
  1320. if "TD stack" not in self.YamlNode.Stacking.keys():
  1321. self.YamlNode.Stacking["TD stack"] = {}
  1322. self.YamlNode.Stacking["TD stack"]["outlier"] = str( self.ui.outlierTestCB.currentText() )
  1323. self.YamlNode.Stacking["TD stack"]["cutoff"] = str( self.ui.MADCutoff.value() )
  1324. self.Log()
  1325. else:
  1326. err_msg = "TD noise cancellation has already been applied!"
  1327. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1328. err_msg)
  1329. return
  1330. self.lock("time-domain smart stack")
  1331. thread.start_new_thread(self.RAWDataProc.TDSmartStack, \
  1332. (str(self.ui.outlierTestCB.currentText()), \
  1333. self.ui.MADCutoff.value(),
  1334. self.ui.mplwidget))
  1335. def adaptFilter(self):
  1336. self.lock("TD noise cancellation filter")
  1337. # Log processing
  1338. Adapt = OrderedDict()
  1339. Adapt["STEP " + str(len(self.YamlNode.Processing)) ] = "TD noise cancellation"
  1340. #print(Adapt) # this locks STEP in as first...
  1341. Adapt["n_Taps"] = self.ui.MTapsSpinBox.value()
  1342. Adapt["lambda"] = self.ui.adaptLambdaSpinBox.value()
  1343. Adapt["truncate"] = self.ui.adaptTruncateSpinBox.value()
  1344. Adapt["mu"] = self.ui.adaptMuSpinBox.value()
  1345. Adapt["PCA"] = self.ui.PCAComboBox.currentText()
  1346. #Adapt # this locsk in the dict ordering...
  1347. #print(Adapt) # this locks in the dict...
  1348. self.YamlNode.Processing.append(Adapt)
  1349. self.Log( )
  1350. thread.start_new_thread(self.RAWDataProc.adaptiveFilter, \
  1351. (self.ui.MTapsSpinBox.value(), \
  1352. self.ui.adaptLambdaSpinBox.value(), \
  1353. self.ui.adaptTruncateSpinBox.value(), \
  1354. self.ui.adaptMuSpinBox.value(), \
  1355. str(self.ui.PCAComboBox.currentText()), \
  1356. self.ui.mplwidget))
  1357. def sumDataChans(self):
  1358. self.lock("Summing data channels")
  1359. Sum = OrderedDict()
  1360. Sum["STEP " + str(len(self.YamlNode.Processing))] = "Channel sum"
  1361. self.YamlNode.Processing.append(Sum)
  1362. self.Log( )
  1363. self.dataChan = [self.dataChan[0]]
  1364. self.ui.sumDataBox.setEnabled(False)
  1365. thread.start_new_thread( self.RAWDataProc.sumData, ( self.ui.mplwidget, 7 ) )
  1366. def adaptFilterFD(self):
  1367. self.lock("FD noise cancellation filter")
  1368. thread.start_new_thread(self.RAWDataProc.adaptiveFilterFD, \
  1369. (str(self.ui.windowTypeComboBox.currentText()), \
  1370. self.ui.windowBandwidthSpinBox.value(), \
  1371. self.ui.CentralVSpinBox.value(), \
  1372. self.ui.mplwidget))
  1373. def logGUI(self):
  1374. # You have a race condiditon where the GUI is modifying the Yaml node while you are updating it
  1375. # hence, we need to cache these. More elegant solutions exist
  1376. if "B_0" in self.YamlNode.META:
  1377. B0 = self.YamlNode.META["B_0"]["intensity"]
  1378. Bdec = self.YamlNode.META["B_0"]["dec"]
  1379. Binc = self.YamlNode.META["B_0"]["inc"]
  1380. if "DateTime" in self.YamlNode.META:
  1381. [Date,Time] = self.YamlNode.META["DateTime"].split("T")
  1382. year,month,day = Date.split("-")
  1383. if "Temp" in self.YamlNode.META:
  1384. temp = float(self.YamlNode.META["Temp"])
  1385. if "Coordinates" in self.YamlNode.META:
  1386. UTM = self.YamlNode.META["Coordinates"]["UTM"]
  1387. LatBand = self.YamlNode.META["Coordinates"]["LatBand"]
  1388. Ellipsoid = self.YamlNode.META["Coordinates"]["ellipsoid"]
  1389. # and set
  1390. if "Location" in self.YamlNode.META:
  1391. self.ui.locEdit.setText( self.YamlNode.META["Location"] )
  1392. if "Field Notes" in self.YamlNode.META:
  1393. self.ui.txtComments.setText( self.YamlNode.META["Field Notes"] )
  1394. if "B_0" in self.YamlNode.META:
  1395. self.ui.incSpinBox.setValue( Binc )
  1396. self.ui.decSpinBox.setValue( Bdec )
  1397. self.ui.intensitySpinBox.setValue( B0 )
  1398. if "DateTime" in self.YamlNode.META:
  1399. self.ui.dateEdit.setDate( datetime.date(int(year), int(month), int(day)) )
  1400. self.ui.timeEdit.setTime( datetime.time.fromisoformat( Time ) )
  1401. if "Temp" in self.YamlNode.META:
  1402. self.ui.tempSpinBox.setValue(temp)
  1403. if "Coordinates" in self.YamlNode.META:
  1404. self.ui.UTMzone.setCurrentText(UTM)
  1405. self.ui.latBand.setCurrentText(LatBand)
  1406. self.ui.ellipsoid.setCurrentText(Ellipsoid)
  1407. def logSite(self):
  1408. self.YamlNode.META["Location"] = self.ui.locEdit.text()
  1409. self.YamlNode.META["Coordinates"] = OrderedDict()
  1410. self.YamlNode.META["Coordinates"]["UTM"] = self.ui.UTMzone.currentText()
  1411. self.YamlNode.META["Coordinates"]["LatBand"] = self.ui.latBand.currentText()
  1412. self.YamlNode.META["Coordinates"]["ellipsoid"] = self.ui.ellipsoid.currentText()
  1413. self.YamlNode.META["DateTime"] = self.ui.dateEdit.date().toString("yyyy-MM-dd") + "T" + str( self.ui.timeEdit.time().toString("hh:mm") )
  1414. self.YamlNode.META["Temp"] = self.ui.tempSpinBox.value()
  1415. self.YamlNode.META["B_0"] = OrderedDict()
  1416. self.YamlNode.META["B_0"]["inc"] = self.ui.incSpinBox.value()
  1417. self.YamlNode.META["B_0"]["dec"] = self.ui.decSpinBox.value()
  1418. self.YamlNode.META["B_0"]["intensity"] = self.ui.intensitySpinBox.value()
  1419. self.YamlNode.META["Field Notes"] = self.ui.txtComments.toPlainText()
  1420. self.YamlNode.META["Loops"] = OrderedDict()
  1421. for loop in self.loops:
  1422. print(self.loops[loop])
  1423. self.YamlNode.META["Loops"][loop] = loop + ".pwa"
  1424. self.Log()
  1425. def bandPassFilter(self):
  1426. self.lock("bandpass filter")
  1427. # Log processing
  1428. Band = OrderedDict()
  1429. Band["STEP " + str(len(self.YamlNode.Processing))] = "Bandpass filter"
  1430. Band["central_nu"] = str(self.ui.CentralVSpinBox.value())
  1431. Band["passband"] = str(self.ui.passBandSpinBox.value())
  1432. Band["stopband"] = str(self.ui.stopBandSpinBox.value())
  1433. Band["gpass"] = str(self.ui.gpassSpinBox.value())
  1434. Band["gstop"] = str(self.ui.gstopSpinBox.value())
  1435. Band["type"] = str(self.ui.fTypeComboBox.currentText())
  1436. self.YamlNode.Processing.append(Band)
  1437. self.Log( )
  1438. nv = self.ui.lcdTotalDeadTime.value( ) + self.ui.lcdNumberFTauDead.value()
  1439. self.ui.lcdTotalDeadTime.display( nv )
  1440. thread.start_new_thread(self.RAWDataProc.bandpassFilter, \
  1441. (self.ui.mplwidget, 0, self.ui.plotBP.isChecked() ))
  1442. def downsample(self):
  1443. self.lock("resampling")
  1444. # Log processing
  1445. Resample = OrderedDict()
  1446. Resample["STEP "+ str(len(self.YamlNode.Processing))] = "Resample"
  1447. Resample["downsample factor"] = str(self.ui.downSampleSpinBox.value())
  1448. Resample["truncate length"] = str(self.ui.truncateSpinBox.value())
  1449. self.YamlNode.Processing.append(Resample)
  1450. self.Log( )
  1451. thread.start_new_thread(self.RAWDataProc.downsample, \
  1452. (self.ui.truncateSpinBox.value(), \
  1453. self.ui.downSampleSpinBox.value(), \
  1454. self.ui.dsPlot.isChecked(), \
  1455. self.ui.mplwidget))
  1456. def quadDet(self):
  1457. method = ['trf','dogbox','lm'][int(self.ui.QDMethod.currentIndex())]
  1458. loss = ['linear','soft_l1','cauchy','huber'][int(self.ui.QDLoss.currentIndex())]
  1459. # allow overwrite of Quad Det.
  1460. self.YamlNode.Stacking["Quadrature detection"] = {}
  1461. self.YamlNode.Stacking["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1462. self.YamlNode.Stacking["Quadrature detection"]["method"] = method
  1463. self.YamlNode.Stacking["Quadrature detection"]["loss"] = loss
  1464. self.Log()
  1465. #if "Quadrature detection" not in self.YamlNode.Processing.keys():
  1466. # self.YamlNode.Processing["Quadrature detection"] = {}
  1467. # self.YamlNode.Processing["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1468. # self.Log()
  1469. #else:
  1470. # self.YamlNode.Processing["Quadrature detection"] = {}
  1471. # self.YamlNode.Processing["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1472. # self.Log()
  1473. #err_msg = "Quadrature detection has already been done!"
  1474. #reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1475. # err_msg)
  1476. #return
  1477. self.lock("quadrature detection")
  1478. thread.start_new_thread(self.RAWDataProc.quadDet, \
  1479. (self.ui.trimSpin.value(), method, loss, self.ui.mplwidget))
  1480. self.ui.plotQD.setEnabled(True)
  1481. def plotQD(self):
  1482. self.lock("plot QD")
  1483. thread.start_new_thread(self.RAWDataProc.plotQuadDet, \
  1484. (self.ui.trimSpin.value(), int(self.ui.QDType.currentIndex()), self.ui.mplwidget))
  1485. def gateIntegrate(self):
  1486. if "Gate integrate" not in self.YamlNode.Stacking.keys():
  1487. self.YamlNode.Stacking["Gate integrate"] = {}
  1488. self.YamlNode.Stacking["Gate integrate"]["gpd"] = str(self.ui.GPDspinBox.value( ) )
  1489. self.Log()
  1490. self.lock("gate integration")
  1491. thread.start_new_thread(self.RAWDataProc.gateIntegrate, \
  1492. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), self.ui.mplwidget))
  1493. self.ui.actionExport_Preprocessed_Dataset.setEnabled(True)
  1494. self.ui.plotGI.setEnabled(True)
  1495. def plotGI(self):
  1496. self.lock("plot gate integrate")
  1497. thread.start_new_thread(self.RAWDataProc.plotGateIntegrate, \
  1498. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), \
  1499. self.ui.QDType_2.currentIndex(), self.ui.mplwidget))
  1500. def designFilter(self):
  1501. [bord, fe] = self.RAWDataProc.designFilter( \
  1502. self.ui.CentralVSpinBox.value(), \
  1503. self.ui.passBandSpinBox.value(), \
  1504. self.ui.stopBandSpinBox.value(), \
  1505. self.ui.gpassSpinBox.value(), \
  1506. self.ui.gstopSpinBox.value(), \
  1507. str(self.ui.fTypeComboBox.currentText()),
  1508. self.ui.mplwidget
  1509. )
  1510. self.ui.lcdNumberFilterOrder.display(bord)
  1511. self.ui.lcdNumberFTauDead.display(1e3*fe)
  1512. self.ui.bandPassGO.setEnabled(1)
  1513. ################################################################
  1514. # Hack for MacOS to force refresh of group box and plot
  1515. # this has an undesirable effect that it causes the groupbox to 'jump' up
  1516. # TODO come up with a better solution
  1517. self.ui.mplwidget.hide()
  1518. self.ui.mplwidget.show()
  1519. self.ui.BandPassBox.hide()
  1520. self.ui.BandPassBox.show()
  1521. def windowFilter(self):
  1522. self.lock("window filter")
  1523. # Log processing
  1524. Window = OrderedDict()
  1525. Window["STEP " + str(len(self.YamlNode.Processing))] = "Window filter"
  1526. Window["type"] = str(self.ui.windowTypeComboBox.currentText())
  1527. Window["width"] = str(self.ui.windowBandwidthSpinBox.value())
  1528. Window["centre"] = str(self.ui.CentralVSpinBox.value() )
  1529. Window["trim"] = str(self.ui.windowTrim.isChecked())
  1530. self.YamlNode.Processing.append(Window)
  1531. self.Log( )
  1532. if self.ui.windowTrim.isChecked():
  1533. nv = self.ui.lcdTotalDeadTime.value( ) + self.ui.lcdWinDead.value()
  1534. self.ui.lcdTotalDeadTime.display( nv )
  1535. thread.start_new_thread(self.RAWDataProc.windowFilter, \
  1536. (str(self.ui.windowTypeComboBox.currentText()), \
  1537. self.ui.windowBandwidthSpinBox.value(), \
  1538. self.ui.CentralVSpinBox.value(), \
  1539. self.ui.windowTrim.isChecked(), \
  1540. self.ui.mplwidget))
  1541. def designFDFilter(self):
  1542. mPulse = "None"
  1543. if u"Pulse 1" in self.RAWDataProc.DATADICT.keys():
  1544. mPulse = u"Pulse 1"
  1545. elif u"Pulse 2" in self.RAWDataProc.DATADICT.keys():
  1546. mPulse = u"Pulse 2"
  1547. a,b,c,d,dead,ndead = self.RAWDataProc.computeWindow( \
  1548. mPulse,
  1549. self.ui.windowBandwidthSpinBox.value(), \
  1550. self.ui.CentralVSpinBox.value(), \
  1551. str(self.ui.windowTypeComboBox.currentText()), \
  1552. self.ui.mplwidget )
  1553. self.ui.lcdWinDead.display(dead)
  1554. ################################################################
  1555. # Hack for MacOS to force refresh of group box and plot
  1556. # this has an undesirable effect that it causes the groupbox to 'jump' up
  1557. # TODO come up with a better solution
  1558. self.ui.mplwidget.hide()
  1559. self.ui.mplwidget.show()
  1560. self.ui.windowFilterGroupBox.hide()
  1561. self.ui.windowFilterGroupBox.show()
  1562. def updateProgressBar(self, percent):
  1563. self.ui.barProgress.setValue(percent)
  1564. def updateProc(self):
  1565. if str(self.ui.FIDProcComboBox.currentText()) == "Pulse 1":
  1566. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1567. elif str(self.ui.FIDProcComboBox.currentText()) == "Pulse 2":
  1568. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1569. else:
  1570. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1571. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1572. self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  1573. def doneStatus(self): # unlocks GUI
  1574. self.ui.statusbar.clearMessage ( )
  1575. self.ui.barProgress.hide()
  1576. self.updateProc()
  1577. self.enableAll()
  1578. def lock(self, string):
  1579. self.ui.statusbar.showMessage ( string )
  1580. self.ui.barProgress.show()
  1581. self.ui.barProgress.setValue(0)
  1582. self.disable()
  1583. def unlock(self):
  1584. self.ui.statusbar.clearMessage ( )
  1585. self.ui.barProgress.hide()
  1586. self.enableAll()
  1587. def done(self):
  1588. self.ui.statusbar.showMessage ( "" )
  1589. ################################################################
  1590. ################################################################
  1591. # Boiler plate main function
  1592. import pkg_resources
  1593. from pkg_resources import resource_string
  1594. import matplotlib.image as mpimg
  1595. import matplotlib.pyplot as plt
  1596. from akvo.gui.logo import plotLogo
  1597. def main():
  1598. # splash screen logo
  1599. logo = pkg_resources.resource_filename(__name__, 'akvo.png')
  1600. logo2 = pkg_resources.resource_filename(__name__, 'akvo2.png')
  1601. qApp = QtWidgets.QApplication(sys.argv)
  1602. ssplash = True
  1603. if ssplash:
  1604. pixmap = QtGui.QPixmap(logo)
  1605. splash = QtWidgets.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
  1606. splash.show()
  1607. aw = ApplicationWindow()
  1608. #img=mpimg.imread(logo)
  1609. for ax in [ aw.ui.mplwidget ]:
  1610. ax.fig.clear()
  1611. subplot = ax.fig.add_subplot(211)
  1612. # old logo plot
  1613. ax.fig.patch.set_facecolor( None )
  1614. ax.fig.patch.set_alpha( .0 )
  1615. #subplot.imshow(img)
  1616. #ax.fig.patch.set_visible(False)
  1617. subplot.axis('off')
  1618. plotLogo(subplot)
  1619. subplot.xaxis.set_major_locator(plt.NullLocator())
  1620. subplot.yaxis.set_major_locator(plt.NullLocator())
  1621. subplot2 = ax.fig.add_subplot(212)
  1622. subplot2.text(0.5, 1.,'surface NMR workbench',
  1623. horizontalalignment='center',
  1624. verticalalignment='center',
  1625. size=22,
  1626. transform = subplot2.transAxes)
  1627. subplot2.xaxis.set_major_locator(plt.NullLocator())
  1628. subplot2.yaxis.set_major_locator(plt.NullLocator())
  1629. subplot2.axis('off')
  1630. ax.draw()
  1631. if ssplash:
  1632. splash.showMessage("Loading modules")
  1633. splash.finish(aw)
  1634. #time.sleep(1)
  1635. aw.setWindowTitle("Akvo v"+str(VERSION))
  1636. aw.show()
  1637. qApp.setWindowIcon(QtGui.QIcon(logo2))
  1638. sys.exit(qApp.exec_())
  1639. if __name__ == "__main__":
  1640. main()