Surface NMR processing and inversion GUI
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

akvoGUI.py 88KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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. invDict["NonLinearRefinement"] = self.ui.NLButton.isChecked()
  368. invDict["CalcDOI"] = self.ui.DOIButton.isChecked()
  369. node = yaml.YAML()
  370. kpo = open( "invert.yml", 'w' )
  371. node.dump(invDict, kpo)
  372. callBox = callScript( ) #QtWidgets.QDialog()
  373. callBox.ui = Ui_callScript()
  374. callBox.ui.setupUi( callBox )
  375. callBox.setupQTInv( "invert.yml" )
  376. callBox.exec_()
  377. callBox.show()
  378. def calcK0(self):
  379. try:
  380. with open('.akvo.last.path') as f:
  381. fpath = f.readline()
  382. pass
  383. except IOError as e:
  384. fpath = '.'
  385. #self.K0akvoDataFile = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Datafile File', fpath, r"Akvo datafiles (*.yaml)")[0]
  386. #akvoData = QtWidgets.QFileDialog.getOpenFileName(self, 'Open Datafile File', fpath, r"Akvo datafiles (*.yaml)")[0]
  387. txCoilList = self.ui.txListWidget.selectedItems() #currentItem().text()
  388. txCoils = []
  389. for txCoil in txCoilList:
  390. print("txCoil", txCoil.text())
  391. txCoils.append(txCoil.text())
  392. rxCoilList = self.ui.txListWidget.selectedItems() #currentItem().text()
  393. rxCoils = []
  394. for rxCoil in rxCoilList:
  395. print("rxCoil", rxCoil.text())
  396. rxCoils.append(rxCoil.text())
  397. saveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save kernel as", fpath, r"Merlin KernelV0 (*.akvoK0)")[0]
  398. intDict = dict()
  399. intDict["origin_n"] = self.ui.originN.value()
  400. intDict["origin_e"] = self.ui.originE.value()
  401. intDict["origin_d"] = self.ui.originD.value()
  402. intDict["size_n"] = self.ui.sizeN.value()
  403. intDict["size_e"] = self.ui.sizeE.value()
  404. intDict["size_d"] = self.ui.sizeD.value()
  405. intDict["nLay"] = self.ui.NLayers.value()
  406. intDict["thick1"] = self.ui.thick1.value()
  407. intDict["thickN"] = self.ui.thickN.value()
  408. intDict["Lspacing"] = self.ui.layerSpacing.currentText()
  409. intDict["minLevel"] = self.ui.minLevel.value()
  410. intDict["maxLevel"] = self.ui.maxLevel.value()
  411. intDict["branchTol"] = self.ui.branchTol.value()
  412. intDict["txCoils"] = txCoils
  413. intDict["rxCoils"] = rxCoils
  414. # conductivity model...
  415. #tops = self.ui.layerTableWidget.col(0)
  416. #print("Tops", tops)
  417. tops = []
  418. itop = 0
  419. while self.ui.layerTableWidget.item(itop, 0).text():
  420. tops.append( float(self.ui.layerTableWidget.item(itop,0).text()) )
  421. itop += 1
  422. bots = []
  423. ibot = 0
  424. while self.ui.layerTableWidget.item(ibot, 1).text():
  425. bots.append( float(self.ui.layerTableWidget.item(ibot, 1).text()) )
  426. ibot += 1
  427. sigs = []
  428. isig = 0
  429. while self.ui.layerTableWidget.item(isig, 2).text():
  430. sigs.append( 1./float(self.ui.layerTableWidget.item(isig, 2).text()) )
  431. isig += 1
  432. intDict["tops"] = tops
  433. intDict["bots"] = bots
  434. intDict["sigs"] = sigs
  435. node = yaml.YAML()
  436. kpo = open( "kparams.yml", 'w' )
  437. node.dump(intDict, kpo)
  438. callBox = callScript( ) #QtWidgets.QDialog()
  439. callBox.ui = Ui_callScript()
  440. callBox.ui.setupUi( callBox )
  441. callBox.setupCB( self.K0akvoDataFile, "kparams.yml", saveStr )
  442. callBox.exec_()
  443. callBox.show()
  444. def loopAdd(self):
  445. #print(self.ui.loopLabel.text())
  446. #print(self.ui.loopGeom.currentText())
  447. #print(self.ui.loopType.currentText())
  448. #print( "label len", len(self.ui.loopLabel.text()) )
  449. if len(self.ui.loopLabel.text().strip()) == 0:
  450. Error = QtWidgets.QMessageBox()
  451. Error.setWindowTitle("Error!")
  452. Error.setText("Loop label cannot be blank or repeated")
  453. Error.setDetailedText("Each loop label must be unique and comprise at least one character. Leading and trailing whitespace will be trimmed.")
  454. Error.exec_()
  455. else:
  456. ### Circular loop
  457. if self.ui.loopGeom.currentText() == "Circular":
  458. dialog = QtWidgets.QDialog()
  459. dialog.ui = Ui_circularLoopAdd()
  460. dialog.ui.setupUi(dialog)
  461. dialog.exec_()
  462. dialog.show()
  463. if dialog.result():
  464. cn = dialog.ui.centreNorth.value()
  465. ce = dialog.ui.centreEast.value()
  466. ht = dialog.ui.loopHeight.value()
  467. rad = dialog.ui.loopRadius.value()
  468. turns = dialog.ui.loopTurns.value()
  469. ns = dialog.ui.segments.value()
  470. cwise = dialog.ui.cwiseBox.currentIndex()
  471. #print("cwise", cwise)
  472. #dip = dialog.ui.dip.value()
  473. #azimuth = dialog.ui.az.value()
  474. self.loops[self.ui.loopLabel.text()] = FDEM1D.PolygonalWireAntenna()
  475. self.loops[self.ui.loopLabel.text()].SetNumberOfPoints( dialog.ui.segments.value() + 1 )
  476. self.loops[self.ui.loopLabel.text()].SetNumberOfTurns( dialog.ui.loopTurns.value() )
  477. points = np.linspace(0, 2*np.pi, dialog.ui.segments.value()+1)
  478. for iseg, ipt in enumerate(points):
  479. if cwise == 0:
  480. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn+rad*np.sin(ipt), ce+rad*np.cos(ipt), ht) )
  481. else:
  482. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn-rad*np.sin(ipt), ce+rad*np.cos(ipt), ht) )
  483. self.loops[self.ui.loopLabel.text()].SetNumberOfFrequencies(1)
  484. self.loops[self.ui.loopLabel.text()].SetCurrent(1.)
  485. if self.ui.loopGeom.currentText() == "figure-8":
  486. dialog = QtWidgets.QDialog()
  487. dialog.ui = Ui_figure8LoopAdd()
  488. dialog.ui.setupUi(dialog)
  489. dialog.exec_()
  490. dialog.show()
  491. if dialog.result():
  492. cn1 = dialog.ui.centreNorth1.value()
  493. ce1 = dialog.ui.centreEast1.value()
  494. cn2 = dialog.ui.centreNorth2.value()
  495. ce2 = dialog.ui.centreEast2.value()
  496. ht = dialog.ui.loopHeight.value()
  497. rad = dialog.ui.loopRadius.value()
  498. turns = dialog.ui.loopTurns.value()
  499. ns = dialog.ui.segments.value()
  500. cwise = dialog.ui.cwiseBox.currentIndex()
  501. self.loops[self.ui.loopLabel.text()] = FDEM1D.PolygonalWireAntenna()
  502. self.loops[self.ui.loopLabel.text()].SetNumberOfPoints( 2*dialog.ui.segments.value() + 1 )
  503. self.loops[self.ui.loopLabel.text()].SetNumberOfTurns( dialog.ui.loopTurns.value() )
  504. # first loop
  505. points = np.linspace(0, 2*np.pi, dialog.ui.segments.value())
  506. ptsL = []
  507. for iseg, ipt in enumerate(points):
  508. ptsL.append( np.array( [cn1+rad*np.sin(ipt), ce1+rad*np.cos(ipt)] ))
  509. lenP = len(points)
  510. # search for closest point, ugly and not efficient, but it's not critical here
  511. closest = 1e8
  512. iclosest = -1
  513. for iseg, ipt in enumerate(points):
  514. p2 = np.array([cn2-rad*np.sin(ipt), ce2-rad*np.cos(ipt)])
  515. for p1 in ptsL:
  516. dist = np.linalg.norm(p1-p2)
  517. if dist < closest:
  518. closest = dist
  519. iclosest = iseg
  520. points = np.concatenate([points[iclosest::],points[0:iclosest]])
  521. # Fill first loop
  522. point1 = False
  523. for iseg, ipt in enumerate(points):
  524. if cwise == 0:
  525. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn1+rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht) )
  526. pointlast = ( 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. else:
  530. self.loops[self.ui.loopLabel.text()].SetPoint(iseg, ( cn1-rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht) )
  531. if not point1:
  532. point1 = ( cn1-rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht)
  533. pointlast = ( cn1-rad*np.sin(ipt), ce1+rad*np.cos(ipt), ht)
  534. lenP = len(points)
  535. # reorder points again to find nearest point in second loop
  536. closest = 99999
  537. iclosest = -1
  538. for iseg, ipt in enumerate(points):
  539. if cwise == 0:
  540. p2 = np.array([cn2-rad*np.sin(ipt), ce2+rad*np.cos(ipt)])
  541. else:
  542. p2 = np.array([cn2+rad*np.sin(ipt), ce2+rad*np.cos(ipt)])
  543. for p1 in ptsL:
  544. dist = np.linalg.norm(np.array(pointlast[0:2])-p2)
  545. if dist < closest:
  546. closest = dist
  547. iclosest = iseg
  548. points = np.concatenate([points[iclosest::],points[0:iclosest]])
  549. # fill second loop
  550. for iseg, ipt in enumerate(points):
  551. if cwise == 0:
  552. self.loops[self.ui.loopLabel.text()].SetPoint(lenP+iseg, ( cn2-rad*np.sin(ipt), ce2+rad*np.cos(ipt), ht) )
  553. else:
  554. self.loops[self.ui.loopLabel.text()].SetPoint(lenP+iseg, ( cn2+rad*np.sin(ipt), ce2+rad*np.cos(ipt), ht) )
  555. # close loop
  556. self.loops[self.ui.loopLabel.text()].SetPoint(lenP+iseg+1, point1)
  557. self.loops[self.ui.loopLabel.text()].SetNumberOfFrequencies(1)
  558. self.loops[self.ui.loopLabel.text()].SetCurrent(1.)
  559. if self.ui.loopGeom.currentText() == "polygon":
  560. dialog = QtWidgets.QDialog()
  561. dialog.ui = Ui_polygonalLoopAdd()
  562. dialog.ui.setupUi(dialog)
  563. ##########################################################################
  564. # Loop Table
  565. dialog.ui.loopTableWidget.setRowCount(80)
  566. dialog.ui.loopTableWidget.setColumnCount(3)
  567. #dialog.ui.loopTableWidget.horizontalHeader().setSectionResizeMode(0, QtGui.Qt.QHeaderView.Stretch)
  568. dialog.ui.loopTableWidget.setHorizontalHeaderLabels( \
  569. ["Northing [m]","Easting [m]","Height [m]"])
  570. for ir in range(0, dialog.ui.loopTableWidget.rowCount() ):
  571. for ic in range(0, 3): #dialog.ui.loopTableWidget.columnCount() ):
  572. pCell = QtWidgets.QTableWidgetItem()
  573. #pCell.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
  574. #pCell.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  575. #pCell.setBackground( QtGui.QColor("lightgrey").lighter(110) )
  576. dialog.ui.loopTableWidget.setItem(ir, ic, pCell)
  577. #dialog.ui.loopTableWidget.cellChanged.connect(self.loopCellChanged)
  578. #dialog.ui.loopTableWidget.itemClicked.connect(self.loopCellClicked)
  579. #self.ui.loopTableWidget.cellPressed.connect(self.loopCellChanged)
  580. #self.ui.loopTableWidget.cellPressed.connect(self.loopCellClicked)
  581. dialog.ui.loopTableWidget.setDragDropOverwriteMode(False)
  582. dialog.ui.loopTableWidget.setDragEnabled(False)
  583. #self.ui.loopTableWidget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  584. dialog.ui.loopTableWidget.resizeColumnsToContents()
  585. dialog.exec_()
  586. dialog.show()
  587. if dialog.result():
  588. self.loops[self.ui.loopLabel.text()] = FDEM1D.PolygonalWireAntenna()
  589. self.loops[self.ui.loopLabel.text()].SetNumberOfTurns( dialog.ui.loopTurns.value() )
  590. npts = 0
  591. for ir in range(0, dialog.ui.loopTableWidget.rowCount() ):
  592. if len(dialog.ui.loopTableWidget.item(ir, 0).text()) == 0:
  593. break
  594. npts += 1
  595. self.loops[self.ui.loopLabel.text()].SetNumberOfPoints( npts )
  596. for ir in range( 0, npts ):
  597. self.loops[self.ui.loopLabel.text()].SetPoint(ir, eval(dialog.ui.loopTableWidget.item(ir, 0).text()), \
  598. eval(dialog.ui.loopTableWidget.item(ir, 1).text()), \
  599. eval(dialog.ui.loopTableWidget.item(ir, 2).text()) \
  600. )
  601. self.loops[self.ui.loopLabel.text()].SetNumberOfFrequencies(1)
  602. self.loops[self.ui.loopLabel.text()].SetCurrent(1.)
  603. # general across all types
  604. if dialog.result():
  605. yml = open( self.ui.loopLabel.text() + ".pwa", 'w' )
  606. print( self.loops[self.ui.loopLabel.text()], file=yml)
  607. # update the table
  608. self.ui.txRxTable.setRowCount( len(self.loops.keys()) )
  609. pCell = QtWidgets.QTableWidgetItem()
  610. pCell.setText( self.ui.loopLabel.text() )
  611. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
  612. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 0, pCell)
  613. gCell = QtWidgets.QTableWidgetItem()
  614. gCell.setText( self.ui.loopGeom.currentText() )
  615. gCell.setFlags( QtCore.Qt.ItemIsEnabled )
  616. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 1, gCell)
  617. tCell = QtWidgets.QTableWidgetItem()
  618. tCell.setText( str(dialog.ui.loopTurns.value()) )
  619. tCell.setFlags( QtCore.Qt.ItemIsEnabled )
  620. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 2, tCell)
  621. txCell = QtWidgets.QTableWidgetItem()
  622. txCell.setText( str(self.ui.loopType.currentText()) )
  623. txCell.setFlags( QtCore.Qt.ItemIsEnabled )
  624. self.ui.txRxTable.setItem( len(self.loops.keys())-1, 3, txCell)
  625. def headerBoxShrink(self):
  626. #self.ui.headerFileBox.setVisible(False)
  627. if self.ui.headerFileBox.isChecked( ):
  628. #self.ui.headerFileBox.setMinimumSize(460,250)
  629. self.ui.headerBox2.setVisible(True)
  630. else:
  631. #self.ui.headerFileBox.setMinimumSize(460,50)
  632. self.ui.headerBox2.setVisible(False)
  633. def sigmaCellChanged(self):
  634. self.ui.layerTableWidget.cellChanged.disconnect(self.sigmaCellChanged)
  635. # TODO consider building the model whenever this is called. Would be nice to be able to
  636. # do that. Would require instead dist of T2 I guess.
  637. jj = self.ui.layerTableWidget.currentColumn()
  638. ii = self.ui.layerTableWidget.currentRow()
  639. val = "class 'NoneType'>"
  640. try:
  641. val = eval (str( self.ui.layerTableWidget.item(ii, jj).text() ))
  642. except:
  643. #if jj != 0:
  644. # Error = QtWidgets.QMessageBox()
  645. # Error.setWindowTitle("Error!")
  646. # Error.setText("Non-numeric value encountered")
  647. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  648. return
  649. if jj == 1:
  650. #item.setFlags(QtCore.Qt.ItemIsEnabled)
  651. pCell = self.ui.layerTableWidget.item(ii, jj)
  652. pCell.setBackground( QtGui.QColor("white"))
  653. pCell = self.ui.layerTableWidget.item(ii+1, jj-1)
  654. if str(type(pCell)) == "<class 'NoneType'>":
  655. pCell = QtWidgets.QTableWidgetItem()
  656. pCell.setFlags(QtCore.Qt.ItemIsEnabled)
  657. self.ui.layerTableWidget.setItem(ii+1, jj-1, pCell)
  658. if ii == 0:
  659. pCell.setText(str(val))
  660. #pCell3 = self.ui.layerTableWidget.item(ii+1, jj)
  661. #print ("setting", ii, jj, type(pCell3))
  662. #print ( "setting", ii, jj, type(pCell3))
  663. #pCell3.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  664. #pCell3.setFlags( QtCore.Qt.ItemIsEditable )
  665. elif ii > 0:
  666. val2 = eval (str( self.ui.layerTableWidget.item(ii-1, jj).text() ))
  667. #print ("val2", val2, val, type(val))
  668. #if str(type(pCell)) == "<class 'NoneType'>":
  669. if type(val) == str or val > val2:
  670. pCell.setText(str(val))
  671. else:
  672. Error = QtWidgets.QMessageBox()
  673. Error.setWindowTitle("Error!")
  674. Error.setText("Non-increasing layer detected")
  675. Error.setDetailedText("Each layer interface must be below the one above it.")
  676. Error.exec_()
  677. #err_msg = "Quadrature detection has already been done!"
  678. #reply =QtWidgets.QMessageBox.critical(self, 'Error',
  679. # err_msg)
  680. pCell2 = self.ui.layerTableWidget.item(ii, jj)
  681. pCell2.setText(str(""))
  682. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  683. return
  684. # enable next layer
  685. pCell4 = self.ui.layerTableWidget.item(ii+1, jj)
  686. pCell4.setBackground( QtGui.QColor("lightblue") ) #.lighter(110))
  687. pCell4.setForeground( QtGui.QColor("black"))
  688. pCell4.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  689. pCell5 = self.ui.layerTableWidget.item(ii+1, jj+1)
  690. pCell5.setBackground( QtGui.QColor("white"))
  691. pCell5.setForeground( QtGui.QColor("black"))
  692. pCell5.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  693. if ii == 0 and jj == 0:
  694. pCell = self.ui.layerTableWidget.item(0, 1)
  695. pCell.setBackground(QtGui.QColor("lightblue")) #.lighter(110) )
  696. pCell.setForeground( QtGui.QColor("black"))
  697. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  698. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  699. def plotLoops2(self):
  700. self.ui.mplwidget.reAxH(1)
  701. for loop in self.loops:
  702. POINTS = self.loops[loop].GetPoints().T
  703. self.ui.mplwidget.ax1.plot( POINTS[:,1], POINTS[:,0], label=loop )
  704. self.ui.mplwidget.ax1.spines['right'].set_visible(False)
  705. self.ui.mplwidget.ax1.spines['top'].set_visible(False)
  706. self.ui.mplwidget.ax1.set_xlabel("easting (m)")
  707. self.ui.mplwidget.ax1.set_ylabel("northing (m)")
  708. self.ui.mplwidget.ax1.legend()
  709. self.ui.mplwidget.ax1.set_aspect('equal') #, adjustable='box')
  710. self.ui.mplwidget.draw()
  711. def removeLoop(self):
  712. del self.loops[ self.ui.txRxTable.item( self.ui.txRxTable.currentRow(), 0).text() ]
  713. self.ui.txRxTable.removeRow(self.ui.txRxTable.currentRow())
  714. def about(self):
  715. # TODO proper popup with info
  716. #self.w = MyPopup("""About Akvo \n
  717. # Akvo is an open source project developed primarily by Trevor Irons.
  718. #""")
  719. #self.w.setGeometry(100, 100, 400, 200)
  720. #self.w.show()
  721. #print("ABOUT")
  722. # Just a splash screen for now
  723. logo = pkg_resources.resource_filename(__name__, 'akvo-about.png')
  724. pixmap = QtGui.QPixmap(logo)
  725. self.splash = QtWidgets.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
  726. self.splash.show()
  727. def connectGMRDataProcessor(self):
  728. self.RAWDataProc = mrsurvey.GMRDataProcessor()
  729. self.RAWDataProc.progressTrigger.connect(self.updateProgressBar)
  730. self.RAWDataProc.enableDSPTrigger.connect(self.enableDSP)
  731. self.RAWDataProc.doneTrigger.connect(self.doneStatus)
  732. self.RAWDataProc.updateProcTrigger.connect(self.updateProc)
  733. def openGMRRAWDataset(self):
  734. """ Opens a GMR header file
  735. """
  736. try:
  737. with open('.gmr.last.path') as f:
  738. fpath = f.readline()
  739. pass
  740. except IOError as e:
  741. fpath = '.'
  742. self.headerstr = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', fpath)[0] # arg2 = File Type 'All Files (*)'
  743. self.ui.headerFileTextBrowser.clear()
  744. self.ui.headerFileTextBrowser.append(self.headerstr)
  745. if len(self.headerstr) == 0:
  746. return
  747. # clear the processing log
  748. self.ui.logTextBrowser.clear()
  749. self.logText = [] #MAK 20170126
  750. path,filen=os.path.split(str(self.headerstr))
  751. f = open('.gmr.last.path', 'w')
  752. f.write( str(self.headerstr) ) # prompt last file
  753. self.connectGMRDataProcessor()
  754. self.RAWDataProc.readHeaderFile(str(self.headerstr))
  755. # If we got this far, enable all the widgets
  756. self.ui.lcdNumberTauPulse1.setEnabled(True)
  757. self.ui.lcdNumberNuTx.setEnabled(True)
  758. self.ui.lcdNumberTuneuF.setEnabled(True)
  759. self.ui.lcdNumberSampFreq.setEnabled(True)
  760. self.ui.lcdNumberNQ.setEnabled(True)
  761. self.ui.headerFileBox.setEnabled(True)
  762. self.ui.headerFileBox.setChecked( True )
  763. self.ui.headerBox2.setVisible(True)
  764. self.ui.inputRAWParametersBox.setEnabled(True)
  765. self.ui.loadDataPushButton.setEnabled(True)
  766. # make plots as you import the dataset
  767. self.ui.plotImportCheckBox.setEnabled(True)
  768. self.ui.plotImportCheckBox.setChecked(True)
  769. # Update info from the header into the GUI
  770. self.ui.pulseTypeTextBrowser.clear()
  771. self.ui.pulseTypeTextBrowser.append(self.RAWDataProc.pulseType)
  772. self.ui.lcdNumberNuTx.display(self.RAWDataProc.transFreq)
  773. self.ui.lcdNumberTauPulse1.display(1e3*self.RAWDataProc.pulseLength[0])
  774. self.ui.lcdNumberTuneuF.display(self.RAWDataProc.TuneCapacitance)
  775. self.ui.lcdNumberSampFreq.display(self.RAWDataProc.samp)
  776. self.ui.lcdNumberNQ.display(self.RAWDataProc.nPulseMoments)
  777. self.ui.DeadTimeSpinBox.setValue(1e3*self.RAWDataProc.deadTime)
  778. self.ui.CentralVSpinBox.setValue( self.RAWDataProc.transFreq )
  779. # set the B0 field according to Tx as an initial guess
  780. self.ui.intensitySpinBox.setValue( self.RAWDataProc.transFreq/GAMMAH )
  781. if self.RAWDataProc.pulseType != "FID":
  782. self.ui.lcdNumberTauPulse2.setEnabled(1)
  783. self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  784. self.ui.lcdNumberTauDelay.setEnabled(1)
  785. self.ui.lcdNumberTauDelay.display(1e3*self.RAWDataProc.interpulseDelay)
  786. self.ui.FIDProcComboBox.clear()
  787. if self.RAWDataProc.pulseType == "4PhaseT1" or self.RAWDataProc.pulseType == "T1":
  788. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1")
  789. self.ui.FIDProcComboBox.insertItem(1, "Pulse 2")
  790. self.ui.FIDProcComboBox.insertItem(2, "Both")
  791. self.ui.FIDProcComboBox.setCurrentIndex (1)
  792. elif self.RAWDataProc.pulseType == "FID":
  793. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1")
  794. self.ui.FIDProcComboBox.setCurrentIndex (0)
  795. def ExportPreprocess(self):
  796. """ This method exports to YAML
  797. """
  798. try:
  799. with open('.akvo.last.yaml.path') as f:
  800. fpath = f.readline()
  801. pass
  802. except IOError as e:
  803. fpath = '.'
  804. fdir = os.path.dirname(fpath)
  805. # Pickle the preprocessed data dictionary
  806. SaveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save as", fdir, r"Processed data (*.akvoProcData)")[0]
  807. spath,filen=os.path.split(str(SaveStr))
  808. f = open('.akvo.last.yaml.path', 'w')
  809. f.write( str(spath) ) # prompt last file
  810. INFO = {}
  811. INFO["headerstr"] = str(self.headerstr)
  812. INFO["pulseType"] = self.RAWDataProc.pulseType
  813. INFO["transFreq"] = self.RAWDataProc.transFreq.tolist()
  814. INFO["pulseLength"] = self.RAWDataProc.pulseLength.tolist()
  815. INFO["TuneCapacitance"] = self.RAWDataProc.TuneCapacitance.tolist()
  816. #INFO["samp"] = self.RAWDataProc.samp
  817. INFO["nPulseMoments"] = self.RAWDataProc.nPulseMoments
  818. #INFO["deadTime"] = self.RAWDataProc.deadTime
  819. INFO["processed"] = "Akvo v" + VERSION + ", on " + time.strftime("%d/%m/%Y")
  820. # Pulse current info
  821. ip = 0
  822. INFO["Pulses"] = {}
  823. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  824. qq = []
  825. qv = []
  826. for ipm in range(self.RAWDataProc.DATADICT["nPulseMoments"]):
  827. #for istack in self.RAWDataProc.DATADICT["stacks"]:
  828. # print ("stack q", self.RAWDataProc.DATADICT[pulse]["Q"][ipm,istack-1])
  829. qq.append(np.mean( self.RAWDataProc.DATADICT[pulse]["Q"][ipm,:]) )
  830. qv.append(np.std( self.RAWDataProc.DATADICT[pulse]["Q"][ipm,:]/self.RAWDataProc.pulseLength[ip] ))
  831. qq = np.array(qq)
  832. qv = np.array(qv)
  833. iQ = np.argsort(np.array(qq))
  834. qq = np.array(qq)[iQ]
  835. qv = np.array(qv)[iQ]
  836. INFO["Pulses"][pulse] = {}
  837. INFO["Pulses"][pulse]["units"] = "A"
  838. INFO["Pulses"][pulse]["current"] = VectorXr(qq/self.RAWDataProc.pulseLength[ip])
  839. INFO["Pulses"][pulse]["variance"] = VectorXr(qv)
  840. ip += 1
  841. # Data
  842. if self.RAWDataProc.gated == True:
  843. INFO["Gated"] = {}
  844. INFO["Gated"]["abscissa units"] = "ms"
  845. INFO["Gated"]["data units"] = "nT"
  846. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  847. INFO["Gated"][pulse] = {}
  848. INFO["Gated"][pulse]["abscissa"] = VectorXr( self.RAWDataProc.GATEDABSCISSA )
  849. INFO["Gated"][pulse]["windows"] = VectorXr( self.RAWDataProc.GATEDWINDOW )
  850. for ichan in self.RAWDataProc.DATADICT[pulse]["chan"]:
  851. INFO["Gated"][pulse]["Chan. " + str(ichan)] = {}
  852. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["STD"] = VectorXr( np.std(self.RAWDataProc.GATED[ichan]["NR"], axis=0) )
  853. INFO["Gated"][pulse]["Chan. " + str(ichan)]["STD"] = VectorXr( np.average(self.RAWDataProc.GATED[ichan]["BN"], axis=0) )
  854. for ipm in range(self.RAWDataProc.DATADICT["nPulseMoments"]):
  855. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " CA"] = VectorXr(self.RAWDataProc.GATED[ichan]["CA"][ipm])
  856. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " RE"] = VectorXr(self.RAWDataProc.GATED[ichan]["RE"][ipm])
  857. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " IM"] = VectorXr(self.RAWDataProc.GATED[ichan]["IM"][ipm])
  858. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " IP"] = VectorXr(self.RAWDataProc.GATED[ichan]["IP"][ipm])
  859. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " NR"] = VectorXr(self.RAWDataProc.GATED[ichan]["NR"][ipm])
  860. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " STD" ] = VectorXr(self.RAWDataProc.GATED[ichan]["SIGMA"][ipm])
  861. # we have gated data
  862. # Window edges
  863. # Window centres
  864. with open(SaveStr, 'w') as outfile:
  865. #for line in self.logText:
  866. # outfile.write(line+"\n")
  867. yaml.dump(self.YamlNode, outfile)
  868. yaml.dump(INFO, outfile) #, default_flow_style=False)
  869. def SavePreprocess(self):
  870. #if "Saved" not in self.YamlNode.Processing.keys():
  871. # self.YamlNode.Processing["Saved"] = []
  872. #self.YamlNode.Processing["Saved"].append(datetime.datetime.now().isoformat())
  873. #self.Log()
  874. import pickle, os
  875. try:
  876. with open('.akvo.last.path') as f:
  877. fpath = f.readline()
  878. pass
  879. except IOError as e:
  880. fpath = '.'
  881. fdir = os.path.dirname(fpath)
  882. # Pickle the preprocessed data dictionary
  883. SaveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save as", fdir, r"Pickle (*.dmp)")
  884. spath,filen=os.path.split(str(SaveStr[0]))
  885. f = open('.akvo.last.path', 'w')
  886. f.write( str(spath) ) # prompt last file
  887. save = open(SaveStr[0], 'wb')
  888. # Add some extra info
  889. INFO = {}
  890. INFO["pulseType"] = self.RAWDataProc.pulseType
  891. INFO["prePulseDelay"] = self.RAWDataProc.prePulseDelay
  892. INFO["interpulseDelay"] = self.RAWDataProc.interpulseDelay
  893. INFO["transFreq"] = self.RAWDataProc.transFreq
  894. INFO["pulseLength"] = self.RAWDataProc.pulseLength
  895. INFO["TuneCapacitance"] = self.RAWDataProc.TuneCapacitance
  896. INFO["samp"] = self.RAWDataProc.samp
  897. INFO["nPulseMoments"] = self.RAWDataProc.nPulseMoments
  898. INFO["deadTime"] = self.RAWDataProc.deadTime
  899. INFO["transFreq"] = self.RAWDataProc.transFreq
  900. INFO["headerstr"] = str(self.headerstr)
  901. INFO["nDAQVersion"] = self.RAWDataProc.nDAQVersion
  902. INFO["log"] = yaml.dump( self.YamlNode )
  903. TXRX = []
  904. for ir in range(0, self.ui.txRxTable.rowCount() ):
  905. txrx = []
  906. for ic in range(0, self.ui.txRxTable.columnCount() ):
  907. txrx.append( self.ui.txRxTable.item(ir, ic).text() )
  908. TXRX.append(txrx)
  909. INFO["TXRX"] = TXRX
  910. if "Stacking" in self.YamlNode.Stacking.keys():
  911. INFO["sigma"] = self.RawDataProc.sigma
  912. if "Gate integrate" in self.YamlNode.Stacking.keys():
  913. INFO["GATED"] = self.RAWDataProc.GATED
  914. print("META SAVE")
  915. print("INFO log", INFO["log"])
  916. self.RAWDataProc.DATADICT["INFO"] = INFO
  917. pickle.dump(self.RAWDataProc.DATADICT, save)
  918. save.close()
  919. # Export XML file suitable for USGS ScienceBase Data Release
  920. def ExportXML(self):
  921. """ This is a filler function for use by USGS collaborators
  922. """
  923. return 42
  924. def OpenPreprocess(self):
  925. import pickle
  926. try:
  927. with open('.akvo.last.path') as f:
  928. fpath = f.readline()
  929. pass
  930. except IOError as e:
  931. fpath = '.'
  932. #filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', '.')
  933. fpath = QtWidgets.QFileDialog.getOpenFileName(self, 'Open preprocessed file', fpath, r"Pickle Files (*.dmp)")[0]
  934. f = open('.akvo.last.path', 'w')
  935. f.write( str(fpath) ) # prompt last file
  936. self.ui.logTextBrowser.clear()
  937. self.logText = []
  938. if len(fpath) == 0:
  939. return
  940. pfile = open(fpath,'rb')
  941. unpickle = pickle.Unpickler(pfile)
  942. self.connectGMRDataProcessor()
  943. self.RAWDataProc.DATADICT = unpickle.load()
  944. # This line causes Akvo to crash, if the header file is no longer there. We don't need to load the
  945. # file. TODO, need to disable "Load Data" in Load command though, as that is no longer possible.
  946. #self.RAWDataProc.readHeaderFile(self.RAWDataProc.DATADICT["INFO"]["headerstr"])
  947. self.headerstr = self.RAWDataProc.DATADICT["INFO"]["headerstr"]
  948. self.RAWDataProc.pulseType = self.RAWDataProc.DATADICT["INFO"]["pulseType"]
  949. self.RAWDataProc.transFreq = self.RAWDataProc.DATADICT["INFO"]["transFreq"]
  950. self.RAWDataProc.pulseLength = self.RAWDataProc.DATADICT["INFO"]["pulseLength"]
  951. self.RAWDataProc.TuneCapacitance = self.RAWDataProc.DATADICT["INFO"]["TuneCapacitance"]
  952. self.RAWDataProc.samp = self.RAWDataProc.DATADICT["INFO"]["samp"]
  953. self.RAWDataProc.nPulseMoments = self.RAWDataProc.DATADICT["INFO"]["nPulseMoments"]
  954. self.RAWDataProc.deadTime = self.RAWDataProc.DATADICT["INFO"]["deadTime"]
  955. self.RAWDataProc.transFreq = self.RAWDataProc.DATADICT["INFO"]["transFreq"]
  956. self.RAWDataProc.nDAQVersion = self.RAWDataProc.DATADICT["INFO"]["nDAQVersion"]
  957. #self.RAWDataProc.prePulseDelay = self.RAWDataProc.DATADICT["INFO"]["prePulseDelay"]
  958. self.RAWDataProc.dt = 1./self.RAWDataProc.samp
  959. self.dataChan = self.RAWDataProc.DATADICT[ self.RAWDataProc.DATADICT["PULSES"][0] ]["chan"]
  960. # Keep backwards compatibility with prior saved pickles???
  961. #self.ui.logTextBrowser.clear()
  962. #self.ui.logTextBrowser.append( yaml.dump(self.YamlNode)) #, default_flow_style=False) )
  963. #for a in self.logText:
  964. # self.ui.logTextBrowser.append(str(a))
  965. #self.ui.logTextBrowser
  966. #self.ui.logTextBrowser.clear()
  967. #print ( self.RAWDataProc.DATADICT["INFO"]["log"] )
  968. if "TXRX" in self.RAWDataProc.DATADICT["INFO"].keys():
  969. TXRX = self.RAWDataProc.DATADICT["INFO"]["TXRX"]
  970. self.ui.txRxTable.setRowCount( len(TXRX))
  971. for irow, row in enumerate(TXRX):
  972. for icol, val in enumerate(row):
  973. pCell = QtWidgets.QTableWidgetItem()
  974. pCell.setText( val )
  975. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled )
  976. self.ui.txRxTable.setItem(irow, icol, pCell)
  977. self.logText = self.RAWDataProc.DATADICT["INFO"]["log"] # YAML
  978. parse = yaml.load( self.logText, Loader=yaml.Loader )
  979. self.YamlNode = AkvoYamlNode( ) #self.logText )
  980. self.YamlNode.Akvo_VERSION = (yaml.load( self.logText, Loader=yaml.Loader )).Akvo_VERSION
  981. AKVO_VERSION = np.array(self.YamlNode.Akvo_VERSION.split("."), dtype=int)
  982. if AKVO_VERSION[0] >= 1 and AKVO_VERSION[1] >= 2 and AKVO_VERSION[2] >= 3:
  983. self.RAWDataProc.interpulseDelay = self.RAWDataProc.DATADICT["INFO"]["interpulseDelay"]
  984. self.YamlNode.Import = OrderedDict(parse.Import)
  985. self.YamlNode.Processing = list(parse.Processing)
  986. self.YamlNode.Stacking = OrderedDict(parse.Stacking)
  987. self.YamlNode.META = OrderedDict(parse.META)
  988. self.logGUI()
  989. self.Log()
  990. #self.ui.logTextBrowser.append( yaml.dump(self.YamlNode)) #, default_flow_style=False) )
  991. #except KeyError:
  992. # pass
  993. # Remove "Saved" and "Loaded" from processing flow
  994. #if "Loaded" not in self.YamlNode.Processing.keys():
  995. # self.YamlNode.Processing["Loaded"] = []
  996. #self.YamlNode.Processing["Loaded"].append(datetime.datetime.now().isoformat())
  997. #self.Log()
  998. if "Stacking" in self.YamlNode.Stacking.keys():
  999. self.RAWDataProc.sigma = self.RAWDataProc.DATADICT["sigma"]
  1000. # check to see if gate integration has been done, and it's ready to send to Merlin
  1001. if "Gate integrate" in self.YamlNode.Stacking.keys():
  1002. self.RAWDataProc.GATED = self.RAWDataProc.DATADICT["GATED"]
  1003. self.ui.actionExport_Preprocessed_Dataset.setEnabled(True)
  1004. #self.ui.plotGI.setEnabled(True)
  1005. # If we got this far, enable all the widgets
  1006. self.ui.lcdNumberTauPulse1.setEnabled(True)
  1007. self.ui.lcdNumberNuTx.setEnabled(True)
  1008. self.ui.lcdNumberTuneuF.setEnabled(True)
  1009. self.ui.lcdNumberSampFreq.setEnabled(True)
  1010. self.ui.lcdNumberNQ.setEnabled(True)
  1011. self.ui.headerFileBox.setEnabled(True)
  1012. self.ui.headerFileBox.setChecked( True )
  1013. self.headerBoxShrink()
  1014. #self.ui.headerBox2.setVisible(True)
  1015. self.ui.inputRAWParametersBox.setEnabled(False)
  1016. self.ui.loadDataPushButton.setEnabled(True)
  1017. # make plots as you import the datasetmost
  1018. self.ui.plotImportCheckBox.setEnabled(True)
  1019. self.ui.plotImportCheckBox.setChecked(True)
  1020. # enable the LCDs
  1021. self.ui.lcdNumberFID1Length.setEnabled(1)
  1022. self.ui.lcdNumberFID2Length.setEnabled(1)
  1023. self.ui.lcdNumberResampFreq.setEnabled(1)
  1024. self.ui.lcdTotalDeadTime.setEnabled(1)
  1025. # enable META tab
  1026. self.ui.METATab.setEnabled(1)
  1027. self.ui.siteBox.setEnabled(1)
  1028. #self.ui.lcdTotalDeadTime.display( 1e3*self.RAWDataProc.DATADICT["INFO"]["deadTime"] )
  1029. self.ui.headerFileTextBrowser.clear( )
  1030. self.ui.headerFileTextBrowser.append( self.RAWDataProc.DATADICT["INFO"]["headerstr"] )
  1031. if u"Pulse 1" in self.RAWDataProc.DATADICT.keys():
  1032. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1033. self.ui.lcdTotalDeadTime.display( round(1e3*(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 1"]["PULSE_TIMES"][-1]), 3) )
  1034. #print("CALC DEAD", (1e3*(self.RAWDataProc.prePulseDelay))) # - (self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 1"]["PULSE_TIMES"][-1])), 3) )
  1035. if u"Pulse 2" in self.RAWDataProc.DATADICT.keys():
  1036. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1037. self.ui.lcdTotalDeadTime.display( 1e3 * (self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 2"]["PULSE_TIMES"][-1]) )
  1038. # Update info from the header into the GUI
  1039. self.ui.pulseTypeTextBrowser.clear()
  1040. self.ui.pulseTypeTextBrowser.append(self.RAWDataProc.pulseType)
  1041. self.ui.lcdNumberNuTx.display(self.RAWDataProc.transFreq)
  1042. self.ui.lcdNumberTauPulse1.display(1e3*self.RAWDataProc.pulseLength[0])
  1043. self.ui.lcdNumberTuneuF.display(self.RAWDataProc.TuneCapacitance)
  1044. self.ui.lcdNumberResampFreq.display(self.RAWDataProc.samp)
  1045. self.ui.lcdNumberSampFreq.display(50000) # TODO, if non GMR is supported, query
  1046. self.ui.lcdNumberNQ.display(self.RAWDataProc.nPulseMoments)
  1047. self.ui.DeadTimeSpinBox.setValue(1e3*self.RAWDataProc.deadTime)
  1048. self.ui.CentralVSpinBox.setValue( self.RAWDataProc.transFreq )
  1049. if self.RAWDataProc.pulseType != "FID":
  1050. self.ui.lcdNumberTauPulse2.setEnabled(1)
  1051. self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  1052. self.ui.lcdNumberTauDelay.setEnabled(1)
  1053. self.ui.lcdNumberTauDelay.display(1e3*self.RAWDataProc.interpulseDelay)
  1054. self.ui.FIDProcComboBox.clear()
  1055. if self.RAWDataProc.pulseType == "4PhaseT1" or self.RAWDataProc.pulseType == "T1":
  1056. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  1057. self.ui.FIDProcComboBox.insertItem(1, "Pulse 2") #, const QVariant & userData = QVariant() )
  1058. self.ui.FIDProcComboBox.insertItem(2, "Both") #, const QVariant & userData = QVariant() )
  1059. if len( self.RAWDataProc.DATADICT["PULSES"]) == 2:
  1060. self.ui.FIDProcComboBox.setCurrentIndex (2)
  1061. elif self.RAWDataProc.DATADICT["PULSES"][0] == "Pulse 1":
  1062. self.ui.FIDProcComboBox.setCurrentIndex (0)
  1063. else:
  1064. self.ui.FIDProcComboBox.setCurrentIndex (1)
  1065. elif self.RAWDataProc.pulseType == "FID":
  1066. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  1067. self.ui.FIDProcComboBox.setCurrentIndex (0)
  1068. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  1069. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  1070. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  1071. self.RAWDataProc.progressTrigger.connect(self.updateProgressBar)
  1072. self.RAWDataProc.enableDSPTrigger.connect(self.enableDSP)
  1073. self.RAWDataProc.doneTrigger.connect(self.doneStatus)
  1074. self.enableAll()
  1075. def loadRAW(self):
  1076. #################################################
  1077. # Check to make sure we are ready to process
  1078. # Header
  1079. if self.RAWDataProc == None:
  1080. err_msg = "You need to load a header first."
  1081. reply = QtGui.QMessageBox.critical(self, 'Error',
  1082. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  1083. return
  1084. # Stacks
  1085. try:
  1086. self.procStacks = np.array(eval(str("np.r_["+self.ui.stacksLineEdit.text())+"]"))
  1087. except:
  1088. err_msg = "You need to set your stacks correctly.\n" + \
  1089. "This should be a Python Numpy interpretable list\n" + \
  1090. "of stack indices. For example 1:24 or 1:4,8:24"
  1091. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  1092. return
  1093. # Data Channels
  1094. #Chan = np.arange(0,9,1)
  1095. try:
  1096. self.dataChan = np.array(eval(str("np.r_["+self.ui.dataChanLineEdit.text())+"]"))
  1097. except:
  1098. #QMessageBox messageBox;
  1099. #messageBox.critical(0,"Error","An error has occured !");
  1100. #messageBox.setFixedSize(500,200);
  1101. #quit_msg = "Are you sure you want to exit the program?"
  1102. #reply = QtGui.QMessageBox.question(self, 'Message',
  1103. # quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  1104. err_msg = "You need to set your data channels correctly.\n" + \
  1105. "This should be a Python Numpy interpretable list\n" + \
  1106. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  1107. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  1108. "1:3 is not inclusive of 3 and is the same as 1,2 "
  1109. reply = QtGui.QMessageBox.critical(self, 'Error',
  1110. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  1111. return
  1112. #############################
  1113. # Reference Channels
  1114. # TODO make sure no overlap between data and ref channels
  1115. self.refChan = np.array( () )
  1116. if str(self.ui.refChanLineEdit.text()): # != "none":
  1117. try:
  1118. self.refChan = np.array(eval(str("np.r_["+self.ui.refChanLineEdit.text())+"]"))
  1119. except:
  1120. err_msg = "You need to set your reference channels correctly.\n" + \
  1121. "This should be a Python Numpy interpretable list\n" + \
  1122. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  1123. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  1124. "1:3 is not inclusive of 3 and is the same as 1,2 "
  1125. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  1126. return
  1127. #####################################################
  1128. # Load data
  1129. self.lock("loading RAW GMR dataset")
  1130. if self.RAWDataProc.pulseType == "FID":
  1131. self.procThread = thread.start_new_thread(self.RAWDataProc.loadFIDData, \
  1132. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1133. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1134. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1135. elif self.RAWDataProc.pulseType == "4PhaseT1":
  1136. self.procThread = thread.start_new_thread(self.RAWDataProc.load4PhaseT1Data, \
  1137. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1138. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1139. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1140. elif self.RAWDataProc.pulseType == "T1":
  1141. self.procThread = thread.start_new_thread(self.RAWDataProc.loadT1Data, \
  1142. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1143. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1144. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1145. #self.procThread = thread.start_new_thread(self.RAWDataProc.load4PhaseT1Data, \
  1146. # (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  1147. # str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  1148. # 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  1149. self.YamlNode.Import["GMR Header"] = self.headerstr
  1150. self.YamlNode.Import["opened"] = datetime.datetime.now().isoformat()
  1151. self.YamlNode.Import["pulse Type"] = str(self.RAWDataProc.pulseType)
  1152. self.YamlNode.Import["stacks"] = self.procStacks.tolist()
  1153. self.YamlNode.Import["data channels"] = self.dataChan.tolist()
  1154. self.YamlNode.Import["reference channels"] = self.refChan.tolist()
  1155. self.YamlNode.Import["pulse records"] = str(self.ui.FIDProcComboBox.currentText())
  1156. self.YamlNode.Import["instrument dead time"] = (1e-3 * self.ui.DeadTimeSpinBox.value( ))
  1157. self.Log ( )
  1158. # enable META tab
  1159. self.ui.METATab.setEnabled(1)
  1160. self.ui.siteBox.setEnabled(1)
  1161. # should be already done
  1162. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  1163. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  1164. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  1165. #self.ui.ProcessedBox.setEnabled(True)
  1166. self.ui.lcdNumberFID1Length.setEnabled(1)
  1167. self.ui.lcdNumberFID2Length.setEnabled(1)
  1168. self.ui.lcdNumberResampFreq.setEnabled(1)
  1169. self.ui.lcdTotalDeadTime.setEnabled(1)
  1170. self.ui.lcdTotalDeadTime.display( self.ui.DeadTimeSpinBox.value( ) )
  1171. #self.ui.lcdTotalDeadTime.display( round(1e3*(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0]-self.RAWDataProc.DATADICT["Pulse 1"]["PULSE_TIMES"][-1]), 3) )
  1172. #self.ui.lcdNumberFID1Length.display(0)
  1173. #self.ui.lcdNumberFID2Length.display(0)
  1174. #self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  1175. self.mpl_toolbar = NavigationToolbar2QT(self.ui.mplwidget, self.ui.mplwidget)
  1176. self.ui.mplwidget.draw()
  1177. def Log(self):
  1178. #for line in yaml.dump(self.YamlNode, default_flow_style=False):
  1179. #for line in nlogText:
  1180. # self.ui.logTextBrowser.append( line )
  1181. # self.logText.append( line )
  1182. self.ui.logTextBrowser.clear()
  1183. self.ui.logTextBrowser.append( yaml.dump(self.YamlNode ))
  1184. def disable(self):
  1185. self.ui.inputRAWParametersBox.setEnabled(False)
  1186. self.ui.BandPassBox.setEnabled(False)
  1187. self.ui.downSampleGroupBox.setEnabled(False)
  1188. self.ui.windowFilterGroupBox.setEnabled(False)
  1189. self.ui.harmonicBox.setEnabled(False)
  1190. # self.ui.despikeGroupBox.setEnabled(False)
  1191. self.ui.adaptBox.setEnabled(False)
  1192. self.ui.adaptFDBox.setEnabled(False)
  1193. self.ui.qCalcGroupBox.setEnabled(False)
  1194. self.ui.FDSmartStackGroupBox.setEnabled(False)
  1195. self.ui.sumDataBox.setEnabled(False)
  1196. self.ui.qdGroupBox.setEnabled(False)
  1197. self.ui.gateBox.setEnabled(False)
  1198. def enableAll(self):
  1199. self.enableDSP()
  1200. self.enableQC()
  1201. def enableDSP(self):
  1202. # Bandpass filter
  1203. self.ui.BandPassBox.setEnabled(True)
  1204. self.ui.BandPassBox.setChecked(True)
  1205. self.ui.bandPassGO.setEnabled(False) # need to design first
  1206. self.ui.plotBP.setEnabled(True)
  1207. self.ui.plotBP.setChecked(True)
  1208. # downsample
  1209. self.ui.downSampleGroupBox.setEnabled(True)
  1210. self.ui.downSampleGroupBox.setChecked(True)
  1211. # window
  1212. self.ui.windowFilterGroupBox.setEnabled(True)
  1213. self.ui.windowFilterGroupBox.setChecked(True)
  1214. # Despike
  1215. # self.ui.despikeGroupBox.setEnabled(True)
  1216. # self.ui.despikeGroupBox.setChecked(False)
  1217. # Adaptive filtering
  1218. self.ui.adaptBox.setEnabled(True)
  1219. self.ui.adaptBox.setChecked(True)
  1220. # FD Adaptive filtering
  1221. self.ui.adaptFDBox.setEnabled(True)
  1222. self.ui.adaptFDBox.setChecked(False)
  1223. # Harmonic
  1224. self.ui.harmonicBox.setEnabled(True)
  1225. self.ui.harmonicBox.setChecked(True)
  1226. self.LCDHarmonics()
  1227. self.LCDHarmonics2()
  1228. # sum group box
  1229. try:
  1230. if len(self.dataChan) > 1:
  1231. self.ui.sumDataBox.setEnabled(True)
  1232. self.ui.sumDataBox.setChecked(False)
  1233. except:
  1234. pass
  1235. # Quadrature Detect
  1236. self.ui.qdGroupBox.setEnabled(True)
  1237. self.ui.qdGroupBox.setChecked(True)
  1238. self.enableQC()
  1239. def enableQC(self):
  1240. # Q calc
  1241. self.ui.qCalcGroupBox.setEnabled(True)
  1242. self.ui.qCalcGroupBox.setChecked(True)
  1243. # FD SmartStack
  1244. self.ui.FDSmartStackGroupBox.setEnabled(True)
  1245. self.ui.FDSmartStackGroupBox.setChecked(True)
  1246. # Quadrature detect
  1247. try:
  1248. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  1249. np.shape(self.RAWDataProc.DATADICT[pulse]["Q"])
  1250. self.RAWDataProc.DATADICT["stack"]
  1251. self.ui.qdGroupBox.setEnabled(True)
  1252. self.ui.qdGroupBox.setChecked(True)
  1253. except:
  1254. self.ui.qdGroupBox.setEnabled(False)
  1255. self.ui.qdGroupBox.setChecked(False)
  1256. # Gating
  1257. try:
  1258. self.RAWDataProc.DATADICT["CA"]
  1259. self.ui.gateBox.setEnabled(True)
  1260. self.ui.gateBox.setChecked(True)
  1261. except:
  1262. self.ui.gateBox.setEnabled(False)
  1263. self.ui.gateBox.setChecked(False)
  1264. def despikeFilter(self):
  1265. self.lock("despike filter")
  1266. thread.start_new_thread(self.RAWDataProc.despike, \
  1267. (self.ui.windowSpinBox.value(), \
  1268. self.ui.thresholdSpinBox.value(), \
  1269. str(self.ui.replComboBox.currentText()), \
  1270. self.ui.rollOnSpinBox.value(), \
  1271. self.ui.despikeInterpWinSpinBox.value(),
  1272. self.ui.mplwidget))
  1273. def calcQ(self):
  1274. if "Calc Q" not in self.YamlNode.Stacking.keys():
  1275. #print("In CalcQ", yaml.dump(self.YamlNode.Processing) )
  1276. self.YamlNode.Stacking["Calc Q"] = True
  1277. #print( yaml.dump(self.YamlNode.Processing) )
  1278. self.Log()
  1279. else:
  1280. err_msg = "Q values have already been calculated"
  1281. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1282. err_msg)
  1283. return
  1284. self.lock("pulse moment calculation")
  1285. thread.start_new_thread(self.RAWDataProc.effectivePulseMoment, \
  1286. (self.ui.CentralVSpinBox.value(), \
  1287. self.ui.mplwidget))
  1288. def harmonicModel(self):
  1289. self.lock("harmonic noise modelling")
  1290. Harm = OrderedDict()
  1291. Harm["STEP " + str(len(self.YamlNode.Processing))] = "Harmonic modelling"
  1292. Harm["NF"] = str( self.ui.NHarmonicsFreqsSpin.value() )
  1293. Harm["Segments"] = str( self.ui.NSegments.value() )
  1294. Harm["Proc. ref."] = self.ui.harmRef.isChecked()
  1295. if self.ui.searchAll.currentText() == "All":
  1296. Harm["search"] = self.ui.searchAll.currentText()
  1297. Search = False
  1298. else:
  1299. #Harm["search"] = self.ui.searchAll.currentText()
  1300. Harm["search"] = str(self.ui.Nsearch.value())
  1301. Search = self.ui.Nsearch.value()
  1302. if self.ui.boundsCheck.isChecked():
  1303. Harm["Bounds"] = str(self.ui.bounds.value())
  1304. Bounds = self.ui.bounds.value()
  1305. else:
  1306. Harm["Bounds"] = self.ui.boundsCheck.isChecked()
  1307. Bounds = 0
  1308. Harm["f0K1"] = str( self.ui.f0K1Spin.value() )
  1309. Harm["f0KN"] = str( self.ui.f0KNSpin.value() )
  1310. Harm["f0Ks"] = str( self.ui.f0KsSpin.value() )
  1311. Harm["f0"] = str( self.ui.f0Spin.value() )
  1312. if self.ui.NHarmonicsFreqsSpin.value() > 1:
  1313. Harm["f1K1"] = str( self.ui.f1K1Spin.value() )
  1314. Harm["f1KN"] = str( self.ui.f1KNSpin.value() )
  1315. Harm["f1Ks"] = str( self.ui.f1KsSpin.value() )
  1316. Harm["f1"] = str( self.ui.f1Spin.value() )
  1317. self.YamlNode.Processing.append(Harm)
  1318. self.Log()
  1319. thread.start_new_thread(self.RAWDataProc.harmonicModel, \
  1320. ( \
  1321. self.ui.NHarmonicsFreqsSpin.value(), \
  1322. self.ui.f0Spin.value(), \
  1323. self.ui.f0K1Spin.value(), \
  1324. self.ui.f0KNSpin.value(), \
  1325. self.ui.f0KsSpin.value(), \
  1326. self.ui.NSegments.value(), \
  1327. self.ui.f1Spin.value(), \
  1328. self.ui.f1K1Spin.value(), \
  1329. self.ui.f1KNSpin.value(), \
  1330. self.ui.f1KsSpin.value(), \
  1331. Search, \
  1332. Bounds, \
  1333. self.ui.harmRef.isChecked(), \
  1334. self.ui.plotHarmonic.isChecked(), \
  1335. self.ui.mplwidget \
  1336. ) \
  1337. )
  1338. def FDSmartStack(self):
  1339. if "TD stack" not in self.YamlNode.Stacking.keys():
  1340. self.YamlNode.Stacking["TD stack"] = {}
  1341. self.YamlNode.Stacking["TD stack"]["outlier"] = str( self.ui.outlierTestCB.currentText() )
  1342. self.YamlNode.Stacking["TD stack"]["cutoff"] = str( self.ui.MADCutoff.value() )
  1343. self.Log()
  1344. else:
  1345. err_msg = "TD noise cancellation has already been applied!"
  1346. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1347. err_msg)
  1348. return
  1349. self.lock("time-domain smart stack")
  1350. thread.start_new_thread(self.RAWDataProc.TDSmartStack, \
  1351. (str(self.ui.outlierTestCB.currentText()), \
  1352. self.ui.MADCutoff.value(),
  1353. self.ui.mplwidget))
  1354. def adaptFilter(self):
  1355. self.lock("TD noise cancellation filter")
  1356. # Log processing
  1357. Adapt = OrderedDict()
  1358. Adapt["STEP " + str(len(self.YamlNode.Processing)) ] = "TD noise cancellation"
  1359. #print(Adapt) # this locks STEP in as first...
  1360. Adapt["n_Taps"] = self.ui.MTapsSpinBox.value()
  1361. Adapt["lambda"] = self.ui.adaptLambdaSpinBox.value()
  1362. Adapt["truncate"] = self.ui.adaptTruncateSpinBox.value()
  1363. Adapt["mu"] = self.ui.adaptMuSpinBox.value()
  1364. Adapt["PCA"] = self.ui.PCAComboBox.currentText()
  1365. #Adapt # this locsk in the dict ordering...
  1366. #print(Adapt) # this locks in the dict...
  1367. self.YamlNode.Processing.append(Adapt)
  1368. self.Log( )
  1369. thread.start_new_thread(self.RAWDataProc.adaptiveFilter, \
  1370. (self.ui.MTapsSpinBox.value(), \
  1371. self.ui.adaptLambdaSpinBox.value(), \
  1372. self.ui.adaptTruncateSpinBox.value(), \
  1373. self.ui.adaptMuSpinBox.value(), \
  1374. str(self.ui.PCAComboBox.currentText()), \
  1375. self.ui.mplwidget))
  1376. def sumDataChans(self):
  1377. self.lock("Summing data channels")
  1378. Sum = OrderedDict()
  1379. Sum["STEP " + str(len(self.YamlNode.Processing))] = "Channel sum"
  1380. self.YamlNode.Processing.append(Sum)
  1381. self.Log( )
  1382. self.dataChan = [self.dataChan[0]]
  1383. self.ui.sumDataBox.setEnabled(False)
  1384. thread.start_new_thread( self.RAWDataProc.sumData, ( self.ui.mplwidget, 7 ) )
  1385. def adaptFilterFD(self):
  1386. self.lock("FD noise cancellation filter")
  1387. thread.start_new_thread(self.RAWDataProc.adaptiveFilterFD, \
  1388. (str(self.ui.windowTypeComboBox.currentText()), \
  1389. self.ui.windowBandwidthSpinBox.value(), \
  1390. self.ui.CentralVSpinBox.value(), \
  1391. self.ui.mplwidget))
  1392. def logGUI(self):
  1393. # You have a race condiditon where the GUI is modifying the Yaml node while you are updating it
  1394. # hence, we need to cache these. More elegant solutions exist
  1395. if "B_0" in self.YamlNode.META:
  1396. B0 = self.YamlNode.META["B_0"]["intensity"]
  1397. Bdec = self.YamlNode.META["B_0"]["dec"]
  1398. Binc = self.YamlNode.META["B_0"]["inc"]
  1399. if "DateTime" in self.YamlNode.META:
  1400. [Date,Time] = self.YamlNode.META["DateTime"].split("T")
  1401. year,month,day = Date.split("-")
  1402. if "Temp" in self.YamlNode.META:
  1403. temp = float(self.YamlNode.META["Temp"])
  1404. if "Coordinates" in self.YamlNode.META:
  1405. UTM = self.YamlNode.META["Coordinates"]["UTM"]
  1406. LatBand = self.YamlNode.META["Coordinates"]["LatBand"]
  1407. Ellipsoid = self.YamlNode.META["Coordinates"]["ellipsoid"]
  1408. # and set
  1409. if "Location" in self.YamlNode.META:
  1410. self.ui.locEdit.setText( self.YamlNode.META["Location"] )
  1411. if "Field Notes" in self.YamlNode.META:
  1412. self.ui.txtComments.setText( self.YamlNode.META["Field Notes"] )
  1413. if "B_0" in self.YamlNode.META:
  1414. self.ui.incSpinBox.setValue( Binc )
  1415. self.ui.decSpinBox.setValue( Bdec )
  1416. self.ui.intensitySpinBox.setValue( B0 )
  1417. if "DateTime" in self.YamlNode.META:
  1418. self.ui.dateEdit.setDate( datetime.date(int(year), int(month), int(day)) )
  1419. self.ui.timeEdit.setTime( datetime.time.fromisoformat( Time ) )
  1420. if "Temp" in self.YamlNode.META:
  1421. self.ui.tempSpinBox.setValue(temp)
  1422. if "Coordinates" in self.YamlNode.META:
  1423. self.ui.UTMzone.setCurrentText(UTM)
  1424. self.ui.latBand.setCurrentText(LatBand)
  1425. self.ui.ellipsoid.setCurrentText(Ellipsoid)
  1426. def logSite(self):
  1427. self.YamlNode.META["Location"] = self.ui.locEdit.text()
  1428. self.YamlNode.META["Coordinates"] = OrderedDict()
  1429. self.YamlNode.META["Coordinates"]["UTM"] = self.ui.UTMzone.currentText()
  1430. self.YamlNode.META["Coordinates"]["LatBand"] = self.ui.latBand.currentText()
  1431. self.YamlNode.META["Coordinates"]["ellipsoid"] = self.ui.ellipsoid.currentText()
  1432. self.YamlNode.META["DateTime"] = self.ui.dateEdit.date().toString("yyyy-MM-dd") + "T" + str( self.ui.timeEdit.time().toString("hh:mm") )
  1433. self.YamlNode.META["Temp"] = self.ui.tempSpinBox.value()
  1434. self.YamlNode.META["B_0"] = OrderedDict()
  1435. self.YamlNode.META["B_0"]["inc"] = self.ui.incSpinBox.value()
  1436. self.YamlNode.META["B_0"]["dec"] = self.ui.decSpinBox.value()
  1437. self.YamlNode.META["B_0"]["intensity"] = self.ui.intensitySpinBox.value()
  1438. self.YamlNode.META["Field Notes"] = self.ui.txtComments.toPlainText()
  1439. self.YamlNode.META["Loops"] = OrderedDict()
  1440. for loop in self.loops:
  1441. print(self.loops[loop])
  1442. self.YamlNode.META["Loops"][loop] = loop + ".pwa"
  1443. self.Log()
  1444. def bandPassFilter(self):
  1445. self.lock("bandpass filter")
  1446. # Log processing
  1447. Band = OrderedDict()
  1448. Band["STEP " + str(len(self.YamlNode.Processing))] = "Bandpass filter"
  1449. Band["central_nu"] = str(self.ui.CentralVSpinBox.value())
  1450. Band["passband"] = str(self.ui.passBandSpinBox.value())
  1451. Band["stopband"] = str(self.ui.stopBandSpinBox.value())
  1452. Band["gpass"] = str(self.ui.gpassSpinBox.value())
  1453. Band["gstop"] = str(self.ui.gstopSpinBox.value())
  1454. Band["type"] = str(self.ui.fTypeComboBox.currentText())
  1455. self.YamlNode.Processing.append(Band)
  1456. self.Log( )
  1457. nv = self.ui.lcdTotalDeadTime.value( ) + self.ui.lcdNumberFTauDead.value()
  1458. self.ui.lcdTotalDeadTime.display( nv )
  1459. thread.start_new_thread(self.RAWDataProc.bandpassFilter, \
  1460. (self.ui.mplwidget, 0, self.ui.plotBP.isChecked() ))
  1461. def downsample(self):
  1462. self.lock("resampling")
  1463. # Log processing
  1464. Resample = OrderedDict()
  1465. Resample["STEP "+ str(len(self.YamlNode.Processing))] = "Resample"
  1466. Resample["downsample factor"] = str(self.ui.downSampleSpinBox.value())
  1467. Resample["truncate length"] = str(self.ui.truncateSpinBox.value())
  1468. self.YamlNode.Processing.append(Resample)
  1469. self.Log( )
  1470. thread.start_new_thread(self.RAWDataProc.downsample, \
  1471. (self.ui.truncateSpinBox.value(), \
  1472. self.ui.downSampleSpinBox.value(), \
  1473. self.ui.dsPlot.isChecked(), \
  1474. self.ui.mplwidget))
  1475. def quadDet(self):
  1476. method = ['trf','dogbox','lm'][int(self.ui.QDMethod.currentIndex())]
  1477. loss = ['linear','soft_l1','cauchy','huber'][int(self.ui.QDLoss.currentIndex())]
  1478. # allow overwrite of Quad Det.
  1479. self.YamlNode.Stacking["Quadrature detection"] = {}
  1480. self.YamlNode.Stacking["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1481. self.YamlNode.Stacking["Quadrature detection"]["method"] = method
  1482. self.YamlNode.Stacking["Quadrature detection"]["loss"] = loss
  1483. self.Log()
  1484. #if "Quadrature detection" not in self.YamlNode.Processing.keys():
  1485. # self.YamlNode.Processing["Quadrature detection"] = {}
  1486. # self.YamlNode.Processing["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1487. # self.Log()
  1488. #else:
  1489. # self.YamlNode.Processing["Quadrature detection"] = {}
  1490. # self.YamlNode.Processing["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1491. # self.Log()
  1492. #err_msg = "Quadrature detection has already been done!"
  1493. #reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1494. # err_msg)
  1495. #return
  1496. self.lock("quadrature detection")
  1497. thread.start_new_thread(self.RAWDataProc.quadDet, \
  1498. (self.ui.trimSpin.value(), method, loss, self.ui.mplwidget))
  1499. self.ui.plotQD.setEnabled(True)
  1500. def plotQD(self):
  1501. self.lock("plot QD")
  1502. thread.start_new_thread(self.RAWDataProc.plotQuadDet, \
  1503. (self.ui.trimSpin.value(), int(self.ui.QDType.currentIndex()), self.ui.mplwidget))
  1504. def gateIntegrate(self):
  1505. if "Gate integrate" not in self.YamlNode.Stacking.keys():
  1506. self.YamlNode.Stacking["Gate integrate"] = {}
  1507. self.YamlNode.Stacking["Gate integrate"]["gpd"] = str(self.ui.GPDspinBox.value( ) )
  1508. self.Log()
  1509. self.lock("gate integration")
  1510. thread.start_new_thread(self.RAWDataProc.gateIntegrate, \
  1511. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), self.ui.mplwidget))
  1512. self.ui.actionExport_Preprocessed_Dataset.setEnabled(True)
  1513. self.ui.plotGI.setEnabled(True)
  1514. def plotGI(self):
  1515. self.lock("plot gate integrate")
  1516. thread.start_new_thread(self.RAWDataProc.plotGateIntegrate, \
  1517. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), \
  1518. self.ui.QDType_2.currentIndex(), self.ui.mplwidget))
  1519. def designFilter(self):
  1520. [bord, fe] = self.RAWDataProc.designFilter( \
  1521. self.ui.CentralVSpinBox.value(), \
  1522. self.ui.passBandSpinBox.value(), \
  1523. self.ui.stopBandSpinBox.value(), \
  1524. self.ui.gpassSpinBox.value(), \
  1525. self.ui.gstopSpinBox.value(), \
  1526. str(self.ui.fTypeComboBox.currentText()),
  1527. self.ui.mplwidget
  1528. )
  1529. self.ui.lcdNumberFilterOrder.display(bord)
  1530. self.ui.lcdNumberFTauDead.display(1e3*fe)
  1531. self.ui.bandPassGO.setEnabled(1)
  1532. ################################################################
  1533. # Hack for MacOS to force refresh of group box and plot
  1534. # this has an undesirable effect that it causes the groupbox to 'jump' up
  1535. # TODO come up with a better solution
  1536. self.ui.mplwidget.hide()
  1537. self.ui.mplwidget.show()
  1538. self.ui.BandPassBox.hide()
  1539. self.ui.BandPassBox.show()
  1540. def windowFilter(self):
  1541. self.lock("window filter")
  1542. # Log processing
  1543. Window = OrderedDict()
  1544. Window["STEP " + str(len(self.YamlNode.Processing))] = "Window filter"
  1545. Window["type"] = str(self.ui.windowTypeComboBox.currentText())
  1546. Window["width"] = str(self.ui.windowBandwidthSpinBox.value())
  1547. Window["centre"] = str(self.ui.CentralVSpinBox.value() )
  1548. Window["trim"] = str(self.ui.windowTrim.isChecked())
  1549. self.YamlNode.Processing.append(Window)
  1550. self.Log( )
  1551. if self.ui.windowTrim.isChecked():
  1552. nv = self.ui.lcdTotalDeadTime.value( ) + self.ui.lcdWinDead.value()
  1553. self.ui.lcdTotalDeadTime.display( nv )
  1554. thread.start_new_thread(self.RAWDataProc.windowFilter, \
  1555. (str(self.ui.windowTypeComboBox.currentText()), \
  1556. self.ui.windowBandwidthSpinBox.value(), \
  1557. self.ui.CentralVSpinBox.value(), \
  1558. self.ui.windowTrim.isChecked(), \
  1559. self.ui.mplwidget))
  1560. def designFDFilter(self):
  1561. mPulse = "None"
  1562. if u"Pulse 1" in self.RAWDataProc.DATADICT.keys():
  1563. mPulse = u"Pulse 1"
  1564. elif u"Pulse 2" in self.RAWDataProc.DATADICT.keys():
  1565. mPulse = u"Pulse 2"
  1566. a,b,c,d,dead,ndead = self.RAWDataProc.computeWindow( \
  1567. mPulse,
  1568. self.ui.windowBandwidthSpinBox.value(), \
  1569. self.ui.CentralVSpinBox.value(), \
  1570. str(self.ui.windowTypeComboBox.currentText()), \
  1571. self.ui.mplwidget )
  1572. self.ui.lcdWinDead.display(dead)
  1573. ################################################################
  1574. # Hack for MacOS to force refresh of group box and plot
  1575. # this has an undesirable effect that it causes the groupbox to 'jump' up
  1576. # TODO come up with a better solution
  1577. self.ui.mplwidget.hide()
  1578. self.ui.mplwidget.show()
  1579. self.ui.windowFilterGroupBox.hide()
  1580. self.ui.windowFilterGroupBox.show()
  1581. def updateProgressBar(self, percent):
  1582. self.ui.barProgress.setValue(percent)
  1583. def updateProc(self):
  1584. if str(self.ui.FIDProcComboBox.currentText()) == "Pulse 1":
  1585. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1586. elif str(self.ui.FIDProcComboBox.currentText()) == "Pulse 2":
  1587. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1588. else:
  1589. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1590. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1591. self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  1592. def doneStatus(self): # unlocks GUI
  1593. self.ui.statusbar.clearMessage ( )
  1594. self.ui.barProgress.hide()
  1595. self.updateProc()
  1596. self.enableAll()
  1597. def lock(self, string):
  1598. self.ui.statusbar.showMessage ( string )
  1599. self.ui.barProgress.show()
  1600. self.ui.barProgress.setValue(0)
  1601. self.disable()
  1602. def unlock(self):
  1603. self.ui.statusbar.clearMessage ( )
  1604. self.ui.barProgress.hide()
  1605. self.enableAll()
  1606. def done(self):
  1607. self.ui.statusbar.showMessage ( "" )
  1608. ################################################################
  1609. ################################################################
  1610. # Boiler plate main function
  1611. import pkg_resources
  1612. from pkg_resources import resource_string
  1613. import matplotlib.image as mpimg
  1614. import matplotlib.pyplot as plt
  1615. from akvo.gui.logo import plotLogo
  1616. def main():
  1617. # splash screen logo
  1618. logo = pkg_resources.resource_filename(__name__, 'akvo.png')
  1619. logo2 = pkg_resources.resource_filename(__name__, 'akvo2.png')
  1620. qApp = QtWidgets.QApplication(sys.argv)
  1621. ssplash = True
  1622. if ssplash:
  1623. pixmap = QtGui.QPixmap(logo)
  1624. splash = QtWidgets.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
  1625. splash.show()
  1626. aw = ApplicationWindow()
  1627. #img=mpimg.imread(logo)
  1628. for ax in [ aw.ui.mplwidget ]:
  1629. ax.fig.clear()
  1630. subplot = ax.fig.add_subplot(211)
  1631. # old logo plot
  1632. ax.fig.patch.set_facecolor( None )
  1633. ax.fig.patch.set_alpha( .0 )
  1634. #subplot.imshow(img)
  1635. #ax.fig.patch.set_visible(False)
  1636. subplot.axis('off')
  1637. plotLogo(subplot)
  1638. subplot.xaxis.set_major_locator(plt.NullLocator())
  1639. subplot.yaxis.set_major_locator(plt.NullLocator())
  1640. subplot2 = ax.fig.add_subplot(212)
  1641. subplot2.text(0.5, 1.,'surface NMR workbench',
  1642. horizontalalignment='center',
  1643. verticalalignment='center',
  1644. size=22,
  1645. transform = subplot2.transAxes)
  1646. subplot2.xaxis.set_major_locator(plt.NullLocator())
  1647. subplot2.yaxis.set_major_locator(plt.NullLocator())
  1648. subplot2.axis('off')
  1649. ax.draw()
  1650. if ssplash:
  1651. splash.showMessage("Loading modules")
  1652. splash.finish(aw)
  1653. #time.sleep(1)
  1654. aw.setWindowTitle("Akvo v"+str(VERSION))
  1655. aw.show()
  1656. qApp.setWindowIcon(QtGui.QIcon(logo2))
  1657. sys.exit(qApp.exec_())
  1658. if __name__ == "__main__":
  1659. main()