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

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