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

akvoGUI.py 74KB

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