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 75KB

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