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

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