Surface NMR processing and inversion GUI
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

akvoGUI.py 67KB

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