Surface NMR processing and inversion GUI
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

akvoGUI.py 87KB

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