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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. #/usr/bin/env python
  2. import sys
  3. #import readline
  4. try:
  5. from akvo.gui.main_ui import Ui_MainWindow
  6. uicerr = False
  7. except: # Fallback
  8. from akvo.gui.mainui import Ui_MainWindow
  9. uicerr = """
  10. USING THE DEFAULT GUI FILES, AKVO MAY NOT WORK CORRECTLY!
  11. See INSTALL.txt for details regarding GUI configuration
  12. if you are encountering problems.
  13. Clicking ignore will prevent this warning from showing
  14. each time you launch Akvo.
  15. """
  16. import matplotlib
  17. #matplotlib.use("QT4Agg")
  18. from PyQt5 import QtCore, QtGui, QtWidgets
  19. import numpy as np
  20. import time
  21. import os
  22. from copy import deepcopy
  23. from matplotlib.backends.backend_qt4 import NavigationToolbar2QT #as NavigationToolbar
  24. import datetime, time
  25. from akvo.tressel import mrsurvey
  26. import pkg_resources # part of setuptools
  27. version = pkg_resources.require("Akvo")[0].version
  28. import yaml
  29. # Writes out numpy arrays into Eigen vectors as serialized by Lemma
  30. class MatrixXr(yaml.YAMLObject):
  31. yaml_tag = u'MatrixXr'
  32. def __init__(self, rows, cols, data):
  33. self.rows = rows
  34. self.cols = cols
  35. self.data = np.zeros((rows,cols))
  36. def __repr__(self):
  37. return "%s(rows=%r, cols=%r, data=%r)" % (self.__class__.__name__, self.rows, self.cols, self.data)
  38. class VectorXr(yaml.YAMLObject):
  39. yaml_tag = r'VectorXr'
  40. def __init__(self, array):
  41. self.size = np.shape(array)[0]
  42. self.data = array.tolist()
  43. def __repr__(self):
  44. # Converts to numpy array on import
  45. return "np.array(%r)" % (self.data)
  46. from collections import OrderedDict
  47. def represent_ordereddict(dumper, data):
  48. value = []
  49. for item_key, item_value in data.items():
  50. node_key = dumper.represent_data(item_key)
  51. node_value = dumper.represent_data(item_value)
  52. value.append((node_key, node_value))
  53. return yaml.nodes.MappingNode(u'tag:yaml.org,2002:map', value)
  54. yaml.add_representer(OrderedDict, represent_ordereddict)
  55. class AkvoYamlNode(yaml.YAMLObject):
  56. yaml_tag = u'!AkvoData'
  57. def __init__(self):
  58. self.Akvo_VERSION = version
  59. self.Import = {}
  60. self.Processing = OrderedDict()
  61. #self.ProcessingFlow = []
  62. #self.Data = {}
  63. # For going the other way, data import based on Yaml serialization,
  64. def __repr__(self):
  65. return "%s(name=%r, Akvo_VESION=%r, Import=%r, Processing=%r)" % (
  66. self.__class__.__name__, self.Akvo_VERSION, self.Import, OrderedDict(dict(self.Processing)) )
  67. try:
  68. import thread
  69. except ImportError:
  70. import _thread as thread #Py3K compatibility
  71. class MyPopup(QtWidgets.QWidget):
  72. def __init__(self, name):
  73. super().__init__()
  74. self.name = name
  75. self.initUI()
  76. def initUI(self):
  77. lblName = QtWidgets.QLabel(self.name, self)
  78. class ApplicationWindow(QtWidgets.QMainWindow):
  79. def __init__(self):
  80. QtWidgets.QMainWindow.__init__(self)
  81. self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
  82. akvohome = os.path.expanduser("~") + "/.akvo"
  83. if not os.path.exists(akvohome):
  84. os.makedirs(akvohome)
  85. self.ui = Ui_MainWindow()
  86. self.ui.setupUi(self)
  87. if uicerr != False and not os.path.exists(akvohome+"/pyuic-warned"):
  88. reply = QtGui.QMessageBox.warning(self, 'Warning', uicerr, QtGui.QMessageBox.Ok, QtGui.QMessageBox.Ignore)
  89. if reply == 1024: # "0x400" in hex
  90. pass
  91. elif reply == 1048576: # "0x100000" in hex
  92. warn = open( akvohome+"/pyuic-warned" ,"w" )
  93. warn.write("Gui files were not compiled locally using pyuic! Further warnings have been supressed")
  94. warn.close()
  95. self.RAWDataProc = None
  96. self.YamlNode = AkvoYamlNode()
  97. # initialise some stuff
  98. self.ui.lcdNumberTauPulse2.setEnabled(0)
  99. self.ui.lcdNumberTauPulse1.setEnabled(0)
  100. self.ui.lcdNumberNuTx.setEnabled(0)
  101. self.ui.lcdNumberTuneuF.setEnabled(0)
  102. self.ui.lcdNumberSampFreq.setEnabled(0)
  103. self.ui.lcdNumberTauDelay.setEnabled(0)
  104. self.ui.lcdNumberNQ.setEnabled(0)
  105. #MAK 20170126: add in a list to hold processing steps
  106. self.logText = []
  107. ####################
  108. # Make connections #
  109. ####################
  110. # Menu items
  111. self.ui.actionOpen_GMR.triggered.connect(self.openGMRRAWDataset)
  112. self.ui.actionSave_Preprocessed_Dataset.triggered.connect(self.SavePreprocess)
  113. self.ui.actionExport_Preprocessed_Dataset.triggered.connect(self.ExportPreprocess)
  114. self.ui.actionExport_Preprocessed_Dataset.setEnabled(False)
  115. self.ui.actionOpen_Preprocessed_Dataset.triggered.connect(self.OpenPreprocess)
  116. self.ui.actionAboutAkvo.triggered.connect(self.about)
  117. # Buttons
  118. # #QtCore.QObject.connect(self.ui.fullWorkflowPushButton, QtCore.SIGNAL("clicked()"), self.preprocess )
  119. self.ui.loadDataPushButton.pressed.connect(self.loadRAW)
  120. self.ui.sumDataGO.pressed.connect( self.sumDataChans )
  121. self.ui.bandPassGO.pressed.connect( self.bandPassFilter )
  122. self.ui.filterDesignPushButton.pressed.connect( self.designFilter )
  123. self.ui.fdDesignPushButton.pressed.connect( self.designFDFilter )
  124. self.ui.downSampleGO.pressed.connect( self.downsample )
  125. self.ui.windowFilterGO.pressed.connect( self.windowFilter )
  126. # self.ui.despikeGO.pressed.connect( self.despikeFilter ) # use smart stack instead
  127. self.ui.adaptGO.pressed.connect( self.adaptFilter )
  128. self.ui.adaptFDGO.pressed.connect( self.adaptFilterFD )
  129. self.ui.qdGO.pressed.connect( self.quadDet )
  130. self.ui.gateIntegrateGO.pressed.connect( self.gateIntegrate )
  131. self.ui.calcQGO.pressed.connect( self.calcQ )
  132. self.ui.FDSmartStackGO.pressed.connect( self.FDSmartStack )
  133. self.ui.plotQD.setEnabled(False)
  134. self.ui.plotQD.pressed.connect( self.plotQD )
  135. self.ui.plotGI.setEnabled(False)
  136. self.ui.plotGI.pressed.connect( self.plotGI )
  137. # Add progressbar to statusbar
  138. self.ui.barProgress = QtWidgets.QProgressBar()
  139. self.ui.statusbar.addPermanentWidget(self.ui.barProgress, 0);
  140. self.ui.barProgress.setMaximumSize(100, 16777215);
  141. self.ui.barProgress.hide();
  142. self.ui.mplwidget_navigator.setCanvas(self.ui.mplwidget)
  143. self.ui.mplwidget_navigator_2.setCanvas(self.ui.mplwidget_2)
  144. ##########################################################################
  145. # Loop Table
  146. self.ui.loopTableWidget.setRowCount(80)
  147. self.ui.loopTableWidget.setColumnCount(6)
  148. self.ui.loopTableWidget.setHorizontalHeaderLabels( ["ch. tag", \
  149. "Northing [m]","Easting [m]","Height [m]", "Radius","Tx"] )
  150. for ir in range(0, self.ui.loopTableWidget.rowCount() ):
  151. for ic in range(1, self.ui.loopTableWidget.columnCount() ):
  152. pCell = QtWidgets.QTableWidgetItem()
  153. #pCell.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
  154. pCell.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  155. pCell.setBackground( QtGui.QColor("lightgrey").lighter(110) )
  156. self.ui.loopTableWidget.setItem(ir, ic, pCell)
  157. self.ui.loopTableWidget.cellChanged.connect(self.loopCellChanged)
  158. #self.ui.loopTableWidget.cellPressed.connect(self.loopCellChanged)
  159. self.ui.loopTableWidget.itemClicked.connect(self.loopCellClicked)
  160. #self.ui.loopTableWidget.cellPressed.connect(self.loopCellClicked)
  161. self.ui.loopTableWidget.setDragDropOverwriteMode(False)
  162. self.ui.loopTableWidget.setDragEnabled(False)
  163. #self.ui.loopTableWidget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  164. self.loops = {}
  165. ##########################################################################
  166. # layer Table
  167. self.ui.layerTableWidget.setRowCount(80)
  168. self.ui.layerTableWidget.setColumnCount(3)
  169. self.ui.layerTableWidget.setHorizontalHeaderLabels( [r"top [m]", r"bottom [m]", "σ [ Ωm]" ] )
  170. # do we want this
  171. self.ui.layerTableWidget.setDragDropOverwriteMode(False)
  172. self.ui.layerTableWidget.setDragEnabled(True)
  173. self.ui.layerTableWidget.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  174. pCell = QtWidgets.QTableWidgetItem()
  175. pCell.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  176. pCell.setBackground( QtGui.QColor("lightgrey").lighter(110) )
  177. self.ui.layerTableWidget.setItem(0, 1, pCell)
  178. for ir in range(1, self.ui.layerTableWidget.rowCount() ):
  179. for ic in range(0, self.ui.layerTableWidget.columnCount() ):
  180. pCell = QtWidgets.QTableWidgetItem()
  181. #pCell.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
  182. pCell.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  183. pCell.setBackground( QtGui.QColor("lightgrey").lighter(110) )
  184. self.ui.layerTableWidget.setItem(ir, ic, pCell)
  185. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  186. def sigmaCellChanged(self):
  187. self.ui.layerTableWidget.cellChanged.disconnect(self.sigmaCellChanged)
  188. # TODO consider building the model whenever this is called. Would be nice to be able to
  189. # do that. Would require instead dist of T2 I guess.
  190. jj = self.ui.layerTableWidget.currentColumn()
  191. ii = self.ui.layerTableWidget.currentRow()
  192. val = "class 'NoneType'>"
  193. try:
  194. val = eval (str( self.ui.layerTableWidget.item(ii, jj).text() ))
  195. except:
  196. #if jj != 0:
  197. # Error = QtWidgets.QMessageBox()
  198. # Error.setWindowTitle("Error!")
  199. # Error.setText("Non-numeric value encountered")
  200. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  201. return
  202. if jj == 1:
  203. #item.setFlags(QtCore.Qt.ItemIsEnabled)
  204. pCell = self.ui.layerTableWidget.item(ii, jj)
  205. pCell.setBackground( QtGui.QColor("white"))
  206. pCell = self.ui.layerTableWidget.item(ii+1, jj-1)
  207. if str(type(pCell)) == "<class 'NoneType'>":
  208. pCell = QtWidgets.QTableWidgetItem()
  209. pCell.setFlags(QtCore.Qt.ItemIsEnabled)
  210. self.ui.layerTableWidget.setItem(ii+1, jj-1, pCell)
  211. if ii == 0:
  212. pCell.setText(str(val))
  213. #pCell3 = self.ui.layerTableWidget.item(ii+1, jj)
  214. #print ("setting", ii, jj, type(pCell3))
  215. #print ( "setting", ii, jj, type(pCell3))
  216. #pCell3.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  217. #pCell3.setFlags( QtCore.Qt.ItemIsEditable )
  218. elif ii > 0:
  219. val2 = eval (str( self.ui.layerTableWidget.item(ii-1, jj).text() ))
  220. #print ("val2", val2, val, type(val))
  221. #if str(type(pCell)) == "<class 'NoneType'>":
  222. if type(val) == str or val > val2:
  223. pCell.setText(str(val))
  224. else:
  225. Error = QtWidgets.QMessageBox()
  226. Error.setWindowTitle("Error!")
  227. Error.setText("Non-increasing layer detected")
  228. Error.setDetailedText("Each layer interface must be below the one above it.")
  229. Error.exec_()
  230. pCell2 = self.ui.layerTableWidget.item(ii, jj)
  231. pCell2.setText(str(""))
  232. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  233. return
  234. # enable next layer
  235. pCell4 = self.ui.layerTableWidget.item(ii+1, jj)
  236. pCell4.setBackground( QtGui.QColor("lightblue") ) #.lighter(110))
  237. pCell4.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  238. pCell5 = self.ui.layerTableWidget.item(ii+1, jj+1)
  239. pCell5.setBackground( QtGui.QColor("white"))
  240. pCell5.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  241. print("ii", ii, "jj", jj)
  242. if ii == 0 and jj == 0:
  243. pCell = self.ui.layerTableWidget.item(0, 1)
  244. pCell.setBackground( QtGui.QColor("lightblue")) #.lighter(110) )
  245. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  246. self.ui.layerTableWidget.cellChanged.connect(self.sigmaCellChanged)
  247. def loopCellClicked(self, item):
  248. print("checkstate", item.checkState(),item.row())
  249. #self.ui.loopTableWidget.itemClicked.disconnect(self.loopCellClicked)
  250. jj = item.column()
  251. ii = item.row()
  252. tp = type(self.ui.loopTableWidget.item(ii, 0))
  253. print("tp", tp, ii, jj)
  254. if str(tp) == "<class 'NoneType'>":
  255. return
  256. #print("Clicked", ii, jj)
  257. if jj == 5 and self.ui.loopTableWidget.item(ii, 0).text() in self.loops.keys():
  258. #print("jj=5")
  259. self.loops[ self.ui.loopTableWidget.item(ii, 0).text() ]["Tx"] = self.ui.loopTableWidget.item(ii, 5).checkState()
  260. # update surrogates
  261. print("updating surrogates")
  262. for point in self.loops[ self.ui.loopTableWidget.item(ii, 0).text() ]["points"][1:]:
  263. pCell = self.ui.loopTableWidget.item(point, 5)
  264. if self.ui.loopTableWidget.item(ii, 5).checkState():
  265. pCell.setCheckState(QtCore.Qt.Checked);
  266. else:
  267. pCell.setCheckState(QtCore.Qt.Unchecked);
  268. #print( "loops", self.loops[ self.ui.loopTableWidget.item(ii, 0).text() ]["Tx"])
  269. #self.ui.loopTableWidget.itemClicked.connect(self.loopCellClicked)
  270. def loopCellChanged(self):
  271. self.ui.loopTableWidget.cellChanged.disconnect(self.loopCellChanged)
  272. jj = self.ui.loopTableWidget.currentColumn()
  273. ii = self.ui.loopTableWidget.currentRow()
  274. if jj == 0 and len( self.ui.loopTableWidget.item(ii, jj).text().strip()) == 0:
  275. for jjj in range(jj+1,jj+6):
  276. pCell = self.ui.loopTableWidget.item(ii, jjj)
  277. pCell.setBackground( QtGui.QColor("white") )
  278. pCell.setFlags( QtCore.Qt.NoItemFlags | QtCore.Qt.ItemIsUserCheckable ) # not selectable
  279. elif jj == 0 and len( self.ui.loopTableWidget.item(ii, jj).text().strip() ): # ch. tag modified
  280. for jjj in range(jj+1,jj+5):
  281. pCell = self.ui.loopTableWidget.item(ii, jjj)
  282. pCell.setFlags( QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled )
  283. pCell.setBackground( QtGui.QColor("lightblue") )
  284. if self.ui.loopTableWidget.item(ii, jj).text() not in self.loops.keys():
  285. # This is a new loop ID
  286. self.loops[ self.ui.loopTableWidget.item(ii, jj).text() ] = {}
  287. self.loops[ self.ui.loopTableWidget.item(ii, jj).text() ]["Tx"] = self.ui.loopTableWidget.item(ii, 5).checkState()
  288. self.loops[ self.ui.loopTableWidget.item(ii, jj).text() ]["points"] = [ii]
  289. # Transmitter cell
  290. pCell = self.ui.loopTableWidget.item(ii, jj+5)
  291. pCell.setCheckState(QtCore.Qt.Unchecked)
  292. pCell.setFlags( QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled )
  293. pCell.setBackground( QtGui.QColor("lightblue") )
  294. else:
  295. # This is an existing loop ID
  296. self.loops[ self.ui.loopTableWidget.item(ii, jj).text() ]["points"].append( ii )
  297. pCell = self.ui.loopTableWidget.item(ii, jj+5)
  298. pCell.setFlags(QtCore.Qt.NoItemFlags) # not selectable
  299. if self.loops[ self.ui.loopTableWidget.item(ii, 0).text() ]["Tx"]:
  300. pCell.setCheckState(QtCore.Qt.Checked);
  301. else:
  302. pCell.setCheckState(QtCore.Qt.Unchecked);
  303. #pCell.setFlags( )
  304. pCell.setBackground( QtGui.QColor("lightblue") )
  305. self.plotLoops()
  306. self.ui.loopTableWidget.cellChanged.connect(self.loopCellChanged)
  307. def plotLoops(self):
  308. #self.ui.mplwidget_3.fig.clear()
  309. self.ui.mplwidget_3.ax1.clear()
  310. self.ui.mplwidget_3.ax2.clear()
  311. nor = dict()
  312. eas = dict()
  313. dep = dict()
  314. for ii in range( self.ui.loopTableWidget.rowCount() ):
  315. for jj in range( self.ui.loopTableWidget.columnCount() ):
  316. tp = type(self.ui.loopTableWidget.item(ii, jj))
  317. if str(tp) == "<class 'NoneType'>":
  318. pass
  319. elif not len(self.ui.loopTableWidget.item(ii, jj).text()):
  320. pass
  321. else:
  322. if jj == 0:
  323. idx = self.ui.loopTableWidget.item(ii, 0).text()
  324. if idx not in nor.keys():
  325. nor[idx] = list()
  326. eas[idx] = list()
  327. dep[idx] = list()
  328. if jj == 1:
  329. nor[idx].append( eval(self.ui.loopTableWidget.item(ii, 1).text()) )
  330. elif jj == 2:
  331. eas[idx].append( eval(self.ui.loopTableWidget.item(ii, 2).text()) )
  332. elif jj == 3:
  333. dep[idx].append( eval(self.ui.loopTableWidget.item(ii, 3).text()) )
  334. for ii in nor.keys():
  335. try:
  336. self.ui.mplwidget_3.ax1.plot( np.array(nor[ii]), np.array(eas[ii]) )
  337. except:
  338. pass
  339. #self.ui.mplwidget_3.figure.axes().set
  340. plt.gca().set_aspect('equal') #, adjustable='box')
  341. self.ui.mplwidget_3.draw()
  342. def about(self):
  343. # TODO proper popup with info
  344. #self.w = MyPopup("""About Akvo \n
  345. # Akvo is an open source project developed primarily by Trevor Irons.
  346. #""")
  347. #self.w.setGeometry(100, 100, 400, 200)
  348. #self.w.show()
  349. # Just a splash screen for now
  350. logo = pkg_resources.resource_filename(__name__, 'akvo_about.png')
  351. pixmap = QtGui.QPixmap(logo)
  352. self.splash = QtWidgets.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
  353. self.splash.show()
  354. def connectGMRDataProcessor(self):
  355. self.RAWDataProc = mrsurvey.GMRDataProcessor()
  356. self.RAWDataProc.progressTrigger.connect(self.updateProgressBar)
  357. self.RAWDataProc.enableDSPTrigger.connect(self.enableDSP)
  358. self.RAWDataProc.doneTrigger.connect(self.doneStatus)
  359. self.RAWDataProc.updateProcTrigger.connect(self.updateProc)
  360. def openGMRRAWDataset(self):
  361. """ Opens a GMR header file
  362. """
  363. try:
  364. with open('.gmr.last.path') as f:
  365. fpath = f.readline()
  366. pass
  367. except IOError as e:
  368. fpath = '.'
  369. self.headerstr = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', fpath)[0] # arg2 = File Type 'All Files (*)'
  370. self.ui.headerFileTextBrowser.clear()
  371. self.ui.headerFileTextBrowser.append(self.headerstr)
  372. if len(self.headerstr) == 0:
  373. return
  374. # clear the processing log
  375. self.ui.logTextBrowser.clear()
  376. self.logText = [] #MAK 20170126
  377. path,filen=os.path.split(str(self.headerstr))
  378. f = open('.gmr.last.path', 'w')
  379. f.write( str(self.headerstr) ) # prompt last file
  380. self.connectGMRDataProcessor()
  381. self.RAWDataProc.readHeaderFile(str(self.headerstr))
  382. # If we got this far, enable all the widgets
  383. self.ui.lcdNumberTauPulse1.setEnabled(True)
  384. self.ui.lcdNumberNuTx.setEnabled(True)
  385. self.ui.lcdNumberTuneuF.setEnabled(True)
  386. self.ui.lcdNumberSampFreq.setEnabled(True)
  387. self.ui.lcdNumberNQ.setEnabled(True)
  388. self.ui.headerFileBox.setEnabled(True)
  389. self.ui.inputRAWParametersBox.setEnabled(True)
  390. self.ui.loadDataPushButton.setEnabled(True)
  391. # make plots as you import the dataset
  392. self.ui.plotImportCheckBox.setEnabled(True)
  393. self.ui.plotImportCheckBox.setChecked(True)
  394. # Update info from the header into the GUI
  395. self.ui.pulseTypeTextBrowser.clear()
  396. self.ui.pulseTypeTextBrowser.append(self.RAWDataProc.pulseType)
  397. self.ui.lcdNumberNuTx.display(self.RAWDataProc.transFreq)
  398. self.ui.lcdNumberTauPulse1.display(1e3*self.RAWDataProc.pulseLength[0])
  399. self.ui.lcdNumberTuneuF.display(self.RAWDataProc.TuneCapacitance)
  400. self.ui.lcdNumberSampFreq.display(self.RAWDataProc.samp)
  401. self.ui.lcdNumberNQ.display(self.RAWDataProc.nPulseMoments)
  402. self.ui.DeadTimeSpinBox.setValue(1e3*self.RAWDataProc.deadTime)
  403. self.ui.CentralVSpinBox.setValue( self.RAWDataProc.transFreq )
  404. if self.RAWDataProc.pulseType != "FID":
  405. self.ui.lcdNumberTauPulse2.setEnabled(1)
  406. self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  407. self.ui.lcdNumberTauDelay.setEnabled(1)
  408. self.ui.lcdNumberTauDelay.display(1e3*self.RAWDataProc.interpulseDelay)
  409. self.ui.FIDProcComboBox.clear()
  410. if self.RAWDataProc.pulseType == "4PhaseT1":
  411. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1")
  412. self.ui.FIDProcComboBox.insertItem(1, "Pulse 2")
  413. self.ui.FIDProcComboBox.insertItem(2, "Both")
  414. self.ui.FIDProcComboBox.setCurrentIndex (1)
  415. elif self.RAWDataProc.pulseType == "FID":
  416. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1")
  417. self.ui.FIDProcComboBox.setCurrentIndex (0)
  418. def ExportPreprocess(self):
  419. """ This method export to YAML
  420. """
  421. try:
  422. with open('.akvo.last.yaml.path') as f:
  423. fpath = f.readline()
  424. pass
  425. except IOError as e:
  426. fpath = '.'
  427. fdir = os.path.dirname(fpath)
  428. # Pickle the preprocessed data dictionary
  429. SaveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save as", fdir, r"Processed data (*.yaml)")[0]
  430. spath,filen=os.path.split(str(SaveStr))
  431. f = open('.akvo.last.yaml.path', 'w')
  432. f.write( str(spath) ) # prompt last file
  433. INFO = {}
  434. INFO["headerstr"] = str(self.headerstr)
  435. INFO["pulseType"] = self.RAWDataProc.pulseType
  436. INFO["transFreq"] = self.RAWDataProc.transFreq.tolist()
  437. INFO["pulseLength"] = self.RAWDataProc.pulseLength.tolist()
  438. INFO["TuneCapacitance"] = self.RAWDataProc.TuneCapacitance.tolist()
  439. #INFO["samp"] = self.RAWDataProc.samp
  440. INFO["nPulseMoments"] = self.RAWDataProc.nPulseMoments
  441. #INFO["deadTime"] = self.RAWDataProc.deadTime
  442. INFO["processed"] = "Akvo v. 1.0, on " + time.strftime("%d/%m/%Y")
  443. # Pulse current info
  444. ip = 0
  445. INFO["Pulses"] = {}
  446. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  447. qq = []
  448. qv = []
  449. for ipm in range(self.RAWDataProc.DATADICT["nPulseMoments"]):
  450. #for istack in self.RAWDataProc.DATADICT["stacks"]:
  451. # print ("stack q", self.RAWDataProc.DATADICT[pulse]["Q"][ipm,istack-1])
  452. qq.append(np.mean( self.RAWDataProc.DATADICT[pulse]["Q"][ipm,:]) )
  453. qv.append(np.std( self.RAWDataProc.DATADICT[pulse]["Q"][ipm,:]/self.RAWDataProc.pulseLength[ip] ))
  454. INFO["Pulses"][pulse] = {}
  455. INFO["Pulses"][pulse]["units"] = "A"
  456. INFO["Pulses"][pulse]["current"] = VectorXr(np.array(qq)/self.RAWDataProc.pulseLength[ip])
  457. INFO["Pulses"][pulse]["variance"] = VectorXr(np.array(qv))
  458. ip += 1
  459. # Data
  460. if self.RAWDataProc.gated == True:
  461. INFO["Gated"] = {}
  462. INFO["Gated"]["abscissa units"] = "ms"
  463. INFO["Gated"]["data units"] = "nT"
  464. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  465. INFO["Gated"][pulse] = {}
  466. INFO["Gated"][pulse]["abscissa"] = VectorXr( self.RAWDataProc.GATEDABSCISSA )
  467. INFO["Gated"][pulse]["windows"] = VectorXr( self.RAWDataProc.GATEDWINDOW )
  468. for ichan in self.RAWDataProc.DATADICT[pulse]["chan"]:
  469. INFO["Gated"][pulse]["Chan. " + str(ichan)] = {}
  470. INFO["Gated"][pulse]["Chan. " + str(ichan)]["STD"] = VectorXr( np.std(self.RAWDataProc.GATED[ichan]["NR"], axis=0) )
  471. for ipm in range(self.RAWDataProc.DATADICT["nPulseMoments"]):
  472. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " CA"] = VectorXr(self.RAWDataProc.GATED[ichan]["CA"][ipm])
  473. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " RE"] = VectorXr(self.RAWDataProc.GATED[ichan]["RE"][ipm])
  474. INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " IM"] = VectorXr(self.RAWDataProc.GATED[ichan]["IM"][ipm])
  475. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " IP"] = VectorXr(self.RAWDataProc.GATED[ichan]["IP"][ipm])
  476. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " NR"] = VectorXr(self.RAWDataProc.GATED[ichan]["NR"][ipm])
  477. #INFO["Gated"][pulse]["Chan. " + str(ichan)]["Q-"+str(ipm) + " STD" ] = VectorXr(self.RAWDataProc.GATED[ichan]["SIGMA"][ipm])
  478. # we have gated data
  479. # Window edges
  480. # Window centres
  481. with open(SaveStr, 'w') as outfile:
  482. for line in self.logText:
  483. outfile.write(line+"\n")
  484. yaml.dump(INFO, outfile, default_flow_style=False)
  485. def SavePreprocess(self):
  486. #if "Saved" not in self.YamlNode.Processing.keys():
  487. # self.YamlNode.Processing["Saved"] = []
  488. #self.YamlNode.Processing["Saved"].append(datetime.datetime.now().isoformat())
  489. #self.Log()
  490. import pickle, os
  491. try:
  492. with open('.akvo.last.path') as f:
  493. fpath = f.readline()
  494. pass
  495. except IOError as e:
  496. fpath = '.'
  497. fdir = os.path.dirname(fpath)
  498. # Pickle the preprocessed data dictionary
  499. SaveStr = QtWidgets.QFileDialog.getSaveFileName(self, "Save as", fdir, r"Pickle (*.dmp)")
  500. print(SaveStr)
  501. spath,filen=os.path.split(str(SaveStr[0]))
  502. f = open('.akvo.last.path', 'w')
  503. f.write( str(spath) ) # prompt last file
  504. save = open(SaveStr[0], 'wb')
  505. # Add some extra info
  506. INFO = {}
  507. INFO["pulseType"] = self.RAWDataProc.pulseType
  508. INFO["transFreq"] = self.RAWDataProc.transFreq
  509. INFO["pulseLength"] = self.RAWDataProc.pulseLength
  510. INFO["TuneCapacitance"] = self.RAWDataProc.TuneCapacitance
  511. INFO["samp"] = self.RAWDataProc.samp
  512. INFO["nPulseMoments"] = self.RAWDataProc.nPulseMoments
  513. INFO["deadTime"] = self.RAWDataProc.deadTime
  514. INFO["transFreq"] = self.RAWDataProc.transFreq
  515. INFO["headerstr"] = str(self.headerstr)
  516. INFO["log"] = yaml.dump( self.YamlNode ) #self.logText #MAK 20170127
  517. print ("YAML NODE", yaml.dump( self.YamlNode ) )
  518. self.RAWDataProc.DATADICT["INFO"] = INFO
  519. pickle.dump(self.RAWDataProc.DATADICT, save)
  520. save.close()
  521. # Export XML file suitable for USGS ScienceBase Data Release
  522. def ExportXML(self):
  523. """ This is a filler function for use by USGS collaborators
  524. """
  525. return 42
  526. def OpenPreprocess(self):
  527. import pickle
  528. try:
  529. with open('.akvo.last.path') as f:
  530. fpath = f.readline()
  531. pass
  532. except IOError as e:
  533. fpath = '.'
  534. #filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', '.')
  535. fpath = QtWidgets.QFileDialog.getOpenFileName(self, 'Open preprocessed file', fpath, r"Pickle Files (*.dmp)")[0]
  536. f = open('.akvo.last.path', 'w')
  537. f.write( str(fpath) ) # prompt last file
  538. self.ui.logTextBrowser.clear()
  539. self.logText = []
  540. if len(fpath) == 0:
  541. return
  542. pfile = open(fpath,'rb')
  543. unpickle = pickle.Unpickler(pfile)
  544. self.connectGMRDataProcessor()
  545. self.RAWDataProc.DATADICT = unpickle.load()
  546. self.RAWDataProc.readHeaderFile(self.RAWDataProc.DATADICT["INFO"]["headerstr"])
  547. self.headerstr = self.RAWDataProc.DATADICT["INFO"]["headerstr"]
  548. self.RAWDataProc.pulseType = self.RAWDataProc.DATADICT["INFO"]["pulseType"]
  549. self.RAWDataProc.transFreq = self.RAWDataProc.DATADICT["INFO"]["transFreq"]
  550. self.RAWDataProc.pulseLength = self.RAWDataProc.DATADICT["INFO"]["pulseLength"]
  551. self.RAWDataProc.TuneCapacitance = self.RAWDataProc.DATADICT["INFO"]["TuneCapacitance"]
  552. self.RAWDataProc.samp = self.RAWDataProc.DATADICT["INFO"]["samp"]
  553. self.RAWDataProc.nPulseMoments = self.RAWDataProc.DATADICT["INFO"]["nPulseMoments"]
  554. self.RAWDataProc.deadTime = self.RAWDataProc.DATADICT["INFO"]["deadTime"]
  555. self.RAWDataProc.transFreq = self.RAWDataProc.DATADICT["INFO"]["transFreq"]
  556. self.RAWDataProc.dt = 1./self.RAWDataProc.samp
  557. self.dataChan = self.RAWDataProc.DATADICT[ self.RAWDataProc.DATADICT["PULSES"][0] ]["chan"]
  558. # Keep backwards compatibility with prior saved pickles???
  559. #self.ui.logTextBrowser.clear()
  560. #self.ui.logTextBrowser.append( yaml.dump(self.YamlNode)) #, default_flow_style=False) )
  561. #for a in self.logText:
  562. # self.ui.logTextBrowser.append(str(a))
  563. #self.ui.logTextBrowser
  564. #self.ui.logTextBrowser.clear()
  565. #print ( self.RAWDataProc.DATADICT["INFO"]["log"] )
  566. self.logText = self.RAWDataProc.DATADICT["INFO"]["log"] # YAML
  567. self.YamlNode = yaml.load( self.logText )
  568. #self.ui.logTextBrowser.append( yaml.dump(self.YamlNode)) #, default_flow_style=False) )
  569. #except KeyError:
  570. # pass
  571. # Remove "Saved" and "Loaded" from processing flow
  572. #if "Loaded" not in self.YamlNode.Processing.keys():
  573. # self.YamlNode.Processing["Loaded"] = []
  574. #self.YamlNode.Processing["Loaded"].append(datetime.datetime.now().isoformat())
  575. #self.Log()
  576. # If we got this far, enable all the widgets
  577. self.ui.lcdNumberTauPulse1.setEnabled(True)
  578. self.ui.lcdNumberNuTx.setEnabled(True)
  579. self.ui.lcdNumberTuneuF.setEnabled(True)
  580. self.ui.lcdNumberSampFreq.setEnabled(True)
  581. self.ui.lcdNumberNQ.setEnabled(True)
  582. self.ui.headerFileBox.setEnabled(True)
  583. self.ui.inputRAWParametersBox.setEnabled(True)
  584. self.ui.loadDataPushButton.setEnabled(True)
  585. # make plots as you import the dataset
  586. self.ui.plotImportCheckBox.setEnabled(True)
  587. self.ui.plotImportCheckBox.setChecked(True)
  588. # Update info from the header into the GUI
  589. self.ui.pulseTypeTextBrowser.clear()
  590. self.ui.pulseTypeTextBrowser.append(self.RAWDataProc.pulseType)
  591. self.ui.lcdNumberNuTx.display(self.RAWDataProc.transFreq)
  592. self.ui.lcdNumberTauPulse1.display(1e3*self.RAWDataProc.pulseLength[0])
  593. self.ui.lcdNumberTuneuF.display(self.RAWDataProc.TuneCapacitance)
  594. self.ui.lcdNumberSampFreq.display(self.RAWDataProc.samp)
  595. self.ui.lcdNumberNQ.display(self.RAWDataProc.nPulseMoments)
  596. self.ui.DeadTimeSpinBox.setValue(1e3*self.RAWDataProc.deadTime)
  597. self.ui.CentralVSpinBox.setValue( self.RAWDataProc.transFreq )
  598. if self.RAWDataProc.pulseType != "FID":
  599. self.ui.lcdNumberTauPulse2.setEnabled(1)
  600. self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  601. self.ui.lcdNumberTauDelay.setEnabled(1)
  602. self.ui.lcdNumberTauDelay.display(1e3*self.RAWDataProc.interpulseDelay)
  603. self.ui.FIDProcComboBox.clear()
  604. if self.RAWDataProc.pulseType == "4PhaseT1":
  605. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  606. self.ui.FIDProcComboBox.insertItem(1, "Pulse 2") #, const QVariant & userData = QVariant() )
  607. self.ui.FIDProcComboBox.insertItem(2, "Both") #, const QVariant & userData = QVariant() )
  608. if len( self.RAWDataProc.DATADICT["PULSES"]) == 2:
  609. self.ui.FIDProcComboBox.setCurrentIndex (2)
  610. elif self.RAWDataProc.DATADICT["PULSES"][0] == "Pulse 1":
  611. self.ui.FIDProcComboBox.setCurrentIndex (0)
  612. else:
  613. self.ui.FIDProcComboBox.setCurrentIndex (1)
  614. elif self.RAWDataProc.pulseType == "FID":
  615. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  616. self.ui.FIDProcComboBox.setCurrentIndex (0)
  617. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  618. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  619. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  620. self.RAWDataProc.progressTrigger.connect(self.updateProgressBar)
  621. self.RAWDataProc.enableDSPTrigger.connect(self.enableDSP)
  622. self.RAWDataProc.doneTrigger.connect(self.doneStatus)
  623. self.enableAll()
  624. def loadRAW(self):
  625. #################################################
  626. # Check to make sure we are ready to process
  627. # Header
  628. if self.RAWDataProc == None:
  629. err_msg = "You need to load a header first."
  630. reply = QtGui.QMessageBox.critical(self, 'Error',
  631. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  632. return
  633. # Stacks
  634. try:
  635. self.procStacks = np.array(eval(str("np.r_["+self.ui.stacksLineEdit.text())+"]"))
  636. except:
  637. err_msg = "You need to set your stacks correctly.\n" + \
  638. "This should be a Python Numpy interpretable list\n" + \
  639. "of stack indices. For example 1:24 or 1:4,8:24"
  640. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  641. return
  642. # Data Channels
  643. #Chan = np.arange(0,9,1)
  644. try:
  645. self.dataChan = np.array(eval(str("np.r_["+self.ui.dataChanLineEdit.text())+"]"))
  646. except:
  647. #QMessageBox messageBox;
  648. #messageBox.critical(0,"Error","An error has occured !");
  649. #messageBox.setFixedSize(500,200);
  650. #quit_msg = "Are you sure you want to exit the program?"
  651. #reply = QtGui.QMessageBox.question(self, 'Message',
  652. # quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  653. err_msg = "You need to set your data channels correctly.\n" + \
  654. "This should be a Python Numpy interpretable list\n" + \
  655. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  656. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  657. "1:3 is not inclusive of 3 and is the same as 1,2 "
  658. reply = QtGui.QMessageBox.critical(self, 'Error',
  659. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  660. return
  661. #############################
  662. # Reference Channels
  663. # TODO make sure no overlap between data and ref channels
  664. self.refChan = np.array( () )
  665. if str(self.ui.refChanLineEdit.text()): # != "none":
  666. try:
  667. self.refChan = np.array(eval(str("np.r_["+self.ui.refChanLineEdit.text())+"]"))
  668. except:
  669. err_msg = "You need to set your reference channels correctly.\n" + \
  670. "This should be a Python Numpy interpretable list\n" + \
  671. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  672. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  673. "1:3 is not inclusive of 3 and is the same as 1,2 "
  674. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  675. return
  676. #####################################################
  677. # Load data
  678. self.lock("loading RAW GMR dataset")
  679. if self.RAWDataProc.pulseType == "FID":
  680. self.procThread = thread.start_new_thread(self.RAWDataProc.loadFIDData, \
  681. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  682. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  683. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  684. elif self.RAWDataProc.pulseType == "4PhaseT1":
  685. self.procThread = thread.start_new_thread(self.RAWDataProc.load4PhaseT1Data, \
  686. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  687. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  688. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  689. self.YamlNode.Import["GMR Header"] = self.headerstr
  690. self.YamlNode.Import["opened"] = datetime.datetime.now().isoformat()
  691. self.YamlNode.Import["pulse Type"] = str(self.RAWDataProc.pulseType)
  692. self.YamlNode.Import["stacks"] = self.procStacks.tolist()
  693. self.YamlNode.Import["data channels"] = self.dataChan.tolist()
  694. self.YamlNode.Import["reference channels"] = self.refChan.tolist()
  695. self.YamlNode.Import["pulse records"] = str(self.ui.FIDProcComboBox.currentText())
  696. self.YamlNode.Import["instrument dead time"] = (1e-3 * self.ui.DeadTimeSpinBox.value( ))
  697. self.Log ( )
  698. # should be already done
  699. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  700. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  701. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  702. self.ui.ProcessedBox.setEnabled(True)
  703. self.ui.lcdNumberFID1Length.setEnabled(1)
  704. self.ui.lcdNumberFID2Length.setEnabled(1)
  705. self.ui.lcdNumberResampFreq.setEnabled(1)
  706. self.ui.lcdTotalDeadTime.setEnabled(1)
  707. self.ui.lcdTotalDeadTime.display( self.ui.DeadTimeSpinBox.value( ) )
  708. #self.ui.lcdNumberFID1Length.display(0)
  709. #self.ui.lcdNumberFID2Length.display(0)
  710. #self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  711. self.mpl_toolbar = NavigationToolbar2QT(self.ui.mplwidget, self.ui.mplwidget)
  712. self.ui.mplwidget.draw()
  713. def Log(self):
  714. #for line in yaml.dump(self.YamlNode, default_flow_style=False):
  715. #for line in nlogText:
  716. # self.ui.logTextBrowser.append( line )
  717. # self.logText.append( line )
  718. self.ui.logTextBrowser.clear()
  719. self.ui.logTextBrowser.append( yaml.dump(self.YamlNode)) #, default_flow_style=False) )
  720. def disable(self):
  721. self.ui.BandPassBox.setEnabled(False)
  722. self.ui.downSampleGroupBox.setEnabled(False)
  723. self.ui.windowFilterGroupBox.setEnabled(False)
  724. # self.ui.despikeGroupBox.setEnabled(False)
  725. self.ui.adaptBox.setEnabled(False)
  726. self.ui.adaptFDBox.setEnabled(False)
  727. self.ui.qCalcGroupBox.setEnabled(False)
  728. self.ui.FDSmartStackGroupBox.setEnabled(False)
  729. self.ui.sumDataBox.setEnabled(False)
  730. self.ui.qdGroupBox.setEnabled(False)
  731. self.ui.gateBox.setEnabled(False)
  732. def enableAll(self):
  733. self.enableDSP()
  734. self.enableQC()
  735. def enableDSP(self):
  736. # Bandpass filter
  737. self.ui.BandPassBox.setEnabled(True)
  738. self.ui.BandPassBox.setChecked(True)
  739. self.ui.bandPassGO.setEnabled(False) # need to design first
  740. self.ui.plotBP.setEnabled(True)
  741. self.ui.plotBP.setChecked(True)
  742. # downsample
  743. self.ui.downSampleGroupBox.setEnabled(True)
  744. self.ui.downSampleGroupBox.setChecked(True)
  745. # window
  746. self.ui.windowFilterGroupBox.setEnabled(True)
  747. self.ui.windowFilterGroupBox.setChecked(True)
  748. # Despike
  749. # self.ui.despikeGroupBox.setEnabled(True)
  750. # self.ui.despikeGroupBox.setChecked(False)
  751. # Adaptive filtering
  752. self.ui.adaptBox.setEnabled(True)
  753. self.ui.adaptBox.setChecked(True)
  754. # FD Adaptive filtering
  755. self.ui.adaptFDBox.setEnabled(True)
  756. self.ui.adaptFDBox.setChecked(True)
  757. # sum group box
  758. try:
  759. if len(self.dataChan) > 1:
  760. self.ui.sumDataBox.setEnabled(True)
  761. self.ui.sumDataBox.setChecked(True)
  762. except:
  763. pass
  764. # Quadrature Detect
  765. self.ui.qdGroupBox.setEnabled(True)
  766. self.ui.qdGroupBox.setChecked(True)
  767. self.enableQC()
  768. def enableQC(self):
  769. # Q calc
  770. self.ui.qCalcGroupBox.setEnabled(True)
  771. self.ui.qCalcGroupBox.setChecked(True)
  772. # FD SmartStack
  773. self.ui.FDSmartStackGroupBox.setEnabled(True)
  774. self.ui.FDSmartStackGroupBox.setChecked(True)
  775. # Quadrature detect
  776. try:
  777. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  778. np.shape(self.RAWDataProc.DATADICT[pulse]["Q"])
  779. self.RAWDataProc.DATADICT["stack"]
  780. self.ui.qdGroupBox.setEnabled(True)
  781. self.ui.qdGroupBox.setChecked(True)
  782. except:
  783. self.ui.qdGroupBox.setEnabled(False)
  784. self.ui.qdGroupBox.setChecked(False)
  785. # Gating
  786. try:
  787. self.RAWDataProc.DATADICT["CA"]
  788. self.ui.gateBox.setEnabled(True)
  789. self.ui.gateBox.setChecked(True)
  790. except:
  791. self.ui.gateBox.setEnabled(False)
  792. self.ui.gateBox.setChecked(False)
  793. def despikeFilter(self):
  794. self.lock("despike filter")
  795. thread.start_new_thread(self.RAWDataProc.despike, \
  796. (self.ui.windowSpinBox.value(), \
  797. self.ui.thresholdSpinBox.value(), \
  798. str(self.ui.replComboBox.currentText()), \
  799. self.ui.rollOnSpinBox.value(), \
  800. self.ui.despikeInterpWinSpinBox.value(),
  801. self.ui.mplwidget))
  802. def calcQ(self):
  803. if "Calc Q" not in self.YamlNode.Processing.keys():
  804. self.YamlNode.Processing["Calc Q"] = True
  805. self.Log()
  806. else:
  807. err_msg = "Q values have already been calculated"
  808. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  809. err_msg)
  810. return
  811. self.lock("pulse moment calculation")
  812. thread.start_new_thread(self.RAWDataProc.effectivePulseMoment, \
  813. (self.ui.CentralVSpinBox.value(), \
  814. self.ui.mplwidget_2))
  815. def FDSmartStack(self):
  816. if "TD stack" not in self.YamlNode.Processing.keys():
  817. self.YamlNode.Processing["TD stack"] = {}
  818. self.YamlNode.Processing["TD stack"]["outlier"] = str( self.ui.outlierTestCB.currentText() )
  819. self.YamlNode.Processing["TD stack"]["cutoff"] = str( self.ui.MADCutoff.value() )
  820. self.Log()
  821. else:
  822. err_msg = "TD noise cancellation has already been applied!"
  823. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  824. err_msg)
  825. return
  826. self.lock("time-domain smart stack")
  827. thread.start_new_thread(self.RAWDataProc.TDSmartStack, \
  828. (str(self.ui.outlierTestCB.currentText()), \
  829. self.ui.MADCutoff.value(),
  830. self.ui.mplwidget_2))
  831. def adaptFilter(self):
  832. if "TD noise cancellation" not in self.YamlNode.Processing.keys():
  833. self.YamlNode.Processing["TD noise cancellation"] = {}
  834. self.YamlNode.Processing["TD noise cancellation"]["n_Taps"] = str(self.ui.MTapsSpinBox.value())
  835. self.YamlNode.Processing["TD noise cancellation"]["lambda"] = str(self.ui.adaptLambdaSpinBox.value())
  836. self.YamlNode.Processing["TD noise cancellation"]["truncate"] = str(self.ui.adaptTruncateSpinBox.value())
  837. self.YamlNode.Processing["TD noise cancellation"]["mu"] = str(self.ui.adaptMuSpinBox.value())
  838. self.YamlNode.Processing["TD noise cancellation"]["PCA"] = str(self.ui.PCAComboBox.currentText())
  839. self.Log()
  840. else:
  841. err_msg = "TD noise cancellation has already been applied!"
  842. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  843. err_msg)
  844. return
  845. self.lock("TD noise cancellation filter")
  846. thread.start_new_thread(self.RAWDataProc.adaptiveFilter, \
  847. (self.ui.MTapsSpinBox.value(), \
  848. self.ui.adaptLambdaSpinBox.value(), \
  849. self.ui.adaptTruncateSpinBox.value(), \
  850. self.ui.adaptMuSpinBox.value(), \
  851. str(self.ui.PCAComboBox.currentText()), \
  852. self.ui.mplwidget))
  853. def sumDataChans(self):
  854. if "Data sum" not in self.YamlNode.Processing.keys():
  855. self.YamlNode.Processing["Data sum"] = True
  856. self.Log()
  857. else:
  858. err_msg = "Data channels have already been summed!"
  859. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  860. err_msg)
  861. return
  862. self.lock("Summing data channels")
  863. self.dataChan = [self.dataChan[0]]
  864. self.ui.sumDataBox.setEnabled(False)
  865. thread.start_new_thread( self.RAWDataProc.sumData, ( self.ui.mplwidget, 7 ) )
  866. def adaptFilterFD(self):
  867. self.lock("FD noise cancellation filter")
  868. thread.start_new_thread(self.RAWDataProc.adaptiveFilterFD, \
  869. (str(self.ui.windowTypeComboBox.currentText()), \
  870. self.ui.windowBandwidthSpinBox.value(), \
  871. self.ui.CentralVSpinBox.value(), \
  872. self.ui.mplwidget))
  873. def bandPassFilter(self):
  874. if "Bandpass filter" not in self.YamlNode.Processing.keys():
  875. self.YamlNode.Processing["Bandpass filter"] = {}
  876. self.YamlNode.Processing["Bandpass filter"]["central_nu"] = str(self.ui.CentralVSpinBox.value())
  877. self.YamlNode.Processing["Bandpass filter"]["passband"] = str(self.ui.passBandSpinBox.value())
  878. self.YamlNode.Processing["Bandpass filter"]["stopband"] = str(self.ui.stopBandSpinBox.value())
  879. self.YamlNode.Processing["Bandpass filter"]["gpass"] = str(self.ui.gpassSpinBox.value())
  880. self.YamlNode.Processing["Bandpass filter"]["gstop"] = str(self.ui.gstopSpinBox.value())
  881. self.YamlNode.Processing["Bandpass filter"]["type"] = str(self.ui.fTypeComboBox.currentText())
  882. self.Log()
  883. else:
  884. err_msg = "Bandpass filter has already been applied!"
  885. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  886. err_msg)
  887. return
  888. self.lock("bandpass filter")
  889. nv = self.ui.lcdTotalDeadTime.value( ) + self.ui.lcdNumberFTauDead.value()
  890. self.ui.lcdTotalDeadTime.display( nv )
  891. thread.start_new_thread(self.RAWDataProc.bandpassFilter, \
  892. (self.ui.mplwidget, 0, self.ui.plotBP.isChecked() ))
  893. def downsample(self):
  894. self.lock("resampling")
  895. if "Resample" not in self.YamlNode.Processing.keys():
  896. self.YamlNode.Processing["Resample"] = {}
  897. self.YamlNode.Processing["Resample"]["downsample factor"] = []
  898. self.YamlNode.Processing["Resample"]["truncate length"] = []
  899. self.YamlNode.Processing["Resample"]["downsample factor"].append( str(self.ui.downSampleSpinBox.value() ) )
  900. self.YamlNode.Processing["Resample"]["truncate length"].append( str( self.ui.truncateSpinBox.value() ) )
  901. self.Log( )
  902. thread.start_new_thread(self.RAWDataProc.downsample, \
  903. (self.ui.truncateSpinBox.value(), \
  904. self.ui.downSampleSpinBox.value(),
  905. self.ui.mplwidget))
  906. def quadDet(self):
  907. if "Quadrature detection" not in self.YamlNode.Processing.keys():
  908. self.YamlNode.Processing["Quadrature detection"] = {}
  909. self.YamlNode.Processing["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  910. self.Log()
  911. else:
  912. err_msg = "Quadrature detection has already been done!"
  913. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  914. err_msg)
  915. return
  916. self.lock("quadrature detection")
  917. thread.start_new_thread(self.RAWDataProc.quadDet, \
  918. (self.ui.trimSpin.value(), int(self.ui.QDType.currentIndex()), self.ui.mplwidget_2))
  919. self.ui.plotQD.setEnabled(True)
  920. def plotQD(self):
  921. self.lock("plot QD")
  922. thread.start_new_thread(self.RAWDataProc.plotQuadDet, \
  923. (self.ui.trimSpin.value(), int(self.ui.QDType.currentIndex()), self.ui.mplwidget_2))
  924. def gateIntegrate(self):
  925. if "Gate integrate" not in self.YamlNode.Processing.keys():
  926. self.YamlNode.Processing["Gate integrate"] = {}
  927. self.YamlNode.Processing["Gate integrate"]["gpd"] = str(self.ui.GPDspinBox.value( ) )
  928. self.Log()
  929. self.lock("gate integration")
  930. thread.start_new_thread(self.RAWDataProc.gateIntegrate, \
  931. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), self.ui.mplwidget_2))
  932. self.ui.actionExport_Preprocessed_Dataset.setEnabled(True)
  933. self.ui.plotGI.setEnabled(True)
  934. def plotGI(self):
  935. self.lock("plot gate integrate")
  936. thread.start_new_thread(self.RAWDataProc.plotGateIntegrate, \
  937. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), \
  938. self.ui.QDType_2.currentIndex(), self.ui.mplwidget_2))
  939. def designFilter(self):
  940. [bord, fe] = self.RAWDataProc.designFilter( \
  941. self.ui.CentralVSpinBox.value(), \
  942. self.ui.passBandSpinBox.value(), \
  943. self.ui.stopBandSpinBox.value(), \
  944. self.ui.gpassSpinBox.value(), \
  945. self.ui.gstopSpinBox.value(), \
  946. str(self.ui.fTypeComboBox.currentText()),
  947. self.ui.mplwidget)
  948. self.ui.lcdNumberFilterOrder.display(bord)
  949. self.ui.lcdNumberFTauDead.display(1e3*fe)
  950. #self.ui.lcdNumberFilterOrder.display(bord)
  951. self.ui.bandPassGO.setEnabled(1)
  952. # self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  953. def windowFilter(self):
  954. if "Window filter" not in self.YamlNode.Processing.keys():
  955. self.YamlNode.Processing["Window filter"] = {}
  956. self.YamlNode.Processing["Window filter"]["type"] = str(self.ui.windowTypeComboBox.currentText())
  957. self.YamlNode.Processing["Window filter"]["width"] = str(self.ui.windowBandwidthSpinBox.value())
  958. self.YamlNode.Processing["Window filter"]["centre"] = str(self.ui.CentralVSpinBox.value() )
  959. self.Log()
  960. else:
  961. err_msg = "FD window has already been applied!"
  962. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  963. err_msg)
  964. return
  965. self.lock("window filter")
  966. thread.start_new_thread(self.RAWDataProc.windowFilter, \
  967. (str(self.ui.windowTypeComboBox.currentText()), \
  968. self.ui.windowBandwidthSpinBox.value(), \
  969. self.ui.CentralVSpinBox.value(), \
  970. self.ui.mplwidget))
  971. def designFDFilter(self):
  972. # thread.start_new_thread(self.RAWDataProc.computeWindow, ( \
  973. # "Pulse 1",
  974. # self.ui.windowBandwidthSpinBox.value(), \
  975. # self.ui.CentralVSpinBox.value(), \
  976. # str(self.ui.windowTypeComboBox.currentText()), \
  977. # self.ui.mplwidget ))
  978. a,b,c,d,dead = self.RAWDataProc.computeWindow( \
  979. "Pulse 1",
  980. self.ui.windowBandwidthSpinBox.value(), \
  981. self.ui.CentralVSpinBox.value(), \
  982. str(self.ui.windowTypeComboBox.currentText()), \
  983. self.ui.mplwidget )
  984. self.ui.lcdWinDead.display(dead)
  985. def updateProgressBar(self, percent):
  986. self.ui.barProgress.setValue(percent)
  987. def updateProc(self):
  988. if str(self.ui.FIDProcComboBox.currentText()) == "Pulse 1":
  989. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  990. elif str(self.ui.FIDProcComboBox.currentText()) == "Pulse 2":
  991. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  992. else:
  993. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  994. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  995. self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  996. def doneStatus(self): # unlocks GUI
  997. self.ui.statusbar.clearMessage ( )
  998. self.ui.barProgress.hide()
  999. self.updateProc()
  1000. self.enableAll()
  1001. def lock(self, string):
  1002. self.ui.statusbar.showMessage ( string )
  1003. self.ui.barProgress.show()
  1004. self.ui.barProgress.setValue(0)
  1005. self.disable()
  1006. def unlock(self):
  1007. self.ui.statusbar.clearMessage ( )
  1008. self.ui.barProgress.hide()
  1009. self.enableAll()
  1010. def done(self):
  1011. self.ui.statusbar.showMessage ( "" )
  1012. ################################################################
  1013. ################################################################
  1014. # Boiler plate main function
  1015. import pkg_resources
  1016. from pkg_resources import resource_string
  1017. import matplotlib.image as mpimg
  1018. import matplotlib.pyplot as plt
  1019. def main():
  1020. # splash screen logo
  1021. logo = pkg_resources.resource_filename(__name__, 'akvo.png')
  1022. logo2 = pkg_resources.resource_filename(__name__, 'akvo2.png')
  1023. qApp = QtWidgets.QApplication(sys.argv)
  1024. ssplash = False
  1025. if ssplash:
  1026. pixmap = QtGui.QPixmap(logo)
  1027. splash = QtWidgets.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
  1028. splash.show()
  1029. aw = ApplicationWindow()
  1030. img=mpimg.imread(logo)
  1031. for ax in [ aw.ui.mplwidget ]:
  1032. ax.fig.clear()
  1033. subplot = ax.fig.add_subplot(111)
  1034. ax.fig.patch.set_facecolor( None )
  1035. ax.fig.patch.set_alpha( .0 )
  1036. subplot.imshow(img)
  1037. subplot.xaxis.set_major_locator(plt.NullLocator())
  1038. subplot.yaxis.set_major_locator(plt.NullLocator())
  1039. ax.draw()
  1040. if ssplash:
  1041. splash.showMessage("Loading modules")
  1042. splash.finish(aw)
  1043. #time.sleep(1)
  1044. aw.setWindowTitle("Akvo v"+str(version))
  1045. aw.show()
  1046. qApp.setWindowIcon(QtGui.QIcon(logo2))
  1047. sys.exit(qApp.exec_())
  1048. if __name__ == "__main__":
  1049. main()