Surface NMR processing and inversion GUI
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

akvoGUI.py 66KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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 = OrderedDict((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.headerFileTextBrowser.clear( )
  726. self.ui.headerFileTextBrowser.append( self.RAWDataProc.DATADICT["INFO"]["headerstr"] )
  727. if u"Pulse 1" in self.RAWDataProc.DATADICT.keys():
  728. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  729. if u"Pulse 2" in self.RAWDataProc.DATADICT.keys():
  730. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  731. # Update info from the header into the GUI
  732. self.ui.pulseTypeTextBrowser.clear()
  733. self.ui.pulseTypeTextBrowser.append(self.RAWDataProc.pulseType)
  734. self.ui.lcdNumberNuTx.display(self.RAWDataProc.transFreq)
  735. self.ui.lcdNumberTauPulse1.display(1e3*self.RAWDataProc.pulseLength[0])
  736. self.ui.lcdNumberTuneuF.display(self.RAWDataProc.TuneCapacitance)
  737. self.ui.lcdNumberResampFreq.display(self.RAWDataProc.samp)
  738. self.ui.lcdNumberSampFreq.display(50000) # TODO, if non GMR is supported, query
  739. self.ui.lcdNumberNQ.display(self.RAWDataProc.nPulseMoments)
  740. self.ui.DeadTimeSpinBox.setValue(1e3*self.RAWDataProc.deadTime)
  741. self.ui.CentralVSpinBox.setValue( self.RAWDataProc.transFreq )
  742. if self.RAWDataProc.pulseType != "FID":
  743. self.ui.lcdNumberTauPulse2.setEnabled(1)
  744. self.ui.lcdNumberTauPulse2.display(1e3*self.RAWDataProc.pulseLength[1])
  745. self.ui.lcdNumberTauDelay.setEnabled(1)
  746. self.ui.lcdNumberTauDelay.display(1e3*self.RAWDataProc.interpulseDelay)
  747. self.ui.FIDProcComboBox.clear()
  748. if self.RAWDataProc.pulseType == "4PhaseT1" or self.RAWDataProc.pulseType == "T1":
  749. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  750. self.ui.FIDProcComboBox.insertItem(1, "Pulse 2") #, const QVariant & userData = QVariant() )
  751. self.ui.FIDProcComboBox.insertItem(2, "Both") #, const QVariant & userData = QVariant() )
  752. if len( self.RAWDataProc.DATADICT["PULSES"]) == 2:
  753. self.ui.FIDProcComboBox.setCurrentIndex (2)
  754. elif self.RAWDataProc.DATADICT["PULSES"][0] == "Pulse 1":
  755. self.ui.FIDProcComboBox.setCurrentIndex (0)
  756. else:
  757. self.ui.FIDProcComboBox.setCurrentIndex (1)
  758. elif self.RAWDataProc.pulseType == "FID":
  759. self.ui.FIDProcComboBox.insertItem(0, "Pulse 1") #, const QVariant & userData = QVariant() )
  760. self.ui.FIDProcComboBox.setCurrentIndex (0)
  761. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  762. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  763. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  764. self.RAWDataProc.progressTrigger.connect(self.updateProgressBar)
  765. self.RAWDataProc.enableDSPTrigger.connect(self.enableDSP)
  766. self.RAWDataProc.doneTrigger.connect(self.doneStatus)
  767. self.enableAll()
  768. def loadRAW(self):
  769. #################################################
  770. # Check to make sure we are ready to process
  771. # Header
  772. if self.RAWDataProc == None:
  773. err_msg = "You need to load a header first."
  774. reply = QtGui.QMessageBox.critical(self, 'Error',
  775. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  776. return
  777. # Stacks
  778. try:
  779. self.procStacks = np.array(eval(str("np.r_["+self.ui.stacksLineEdit.text())+"]"))
  780. except:
  781. err_msg = "You need to set your stacks correctly.\n" + \
  782. "This should be a Python Numpy interpretable list\n" + \
  783. "of stack indices. For example 1:24 or 1:4,8:24"
  784. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  785. return
  786. # Data Channels
  787. #Chan = np.arange(0,9,1)
  788. try:
  789. self.dataChan = np.array(eval(str("np.r_["+self.ui.dataChanLineEdit.text())+"]"))
  790. except:
  791. #QMessageBox messageBox;
  792. #messageBox.critical(0,"Error","An error has occured !");
  793. #messageBox.setFixedSize(500,200);
  794. #quit_msg = "Are you sure you want to exit the program?"
  795. #reply = QtGui.QMessageBox.question(self, 'Message',
  796. # quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  797. err_msg = "You need to set your data channels correctly.\n" + \
  798. "This should be a Python Numpy interpretable list\n" + \
  799. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  800. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  801. "1:3 is not inclusive of 3 and is the same as 1,2 "
  802. reply = QtGui.QMessageBox.critical(self, 'Error',
  803. err_msg) #, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
  804. return
  805. #############################
  806. # Reference Channels
  807. # TODO make sure no overlap between data and ref channels
  808. self.refChan = np.array( () )
  809. if str(self.ui.refChanLineEdit.text()): # != "none":
  810. try:
  811. self.refChan = np.array(eval(str("np.r_["+self.ui.refChanLineEdit.text())+"]"))
  812. except:
  813. err_msg = "You need to set your reference channels correctly.\n" + \
  814. "This should be a Python Numpy interpretable list\n" + \
  815. "of indices. For example 1 or 1:3 or 1:3 5\n\n" + \
  816. "valid GMR data channels fall between 1 and 8. Note that\n" +\
  817. "1:3 is not inclusive of 3 and is the same as 1,2 "
  818. QtGui.QMessageBox.critical(self, 'Error', err_msg)
  819. return
  820. #####################################################
  821. # Load data
  822. self.lock("loading RAW GMR dataset")
  823. if self.RAWDataProc.pulseType == "FID":
  824. self.procThread = thread.start_new_thread(self.RAWDataProc.loadFIDData, \
  825. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  826. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  827. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  828. elif self.RAWDataProc.pulseType == "4PhaseT1":
  829. self.procThread = thread.start_new_thread(self.RAWDataProc.load4PhaseT1Data, \
  830. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  831. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  832. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  833. elif self.RAWDataProc.pulseType == "T1":
  834. self.procThread = thread.start_new_thread(self.RAWDataProc.loadT1Data, \
  835. (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  836. str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  837. 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  838. #self.procThread = thread.start_new_thread(self.RAWDataProc.load4PhaseT1Data, \
  839. # (str(self.headerstr), self.procStacks, self.dataChan, self.refChan, \
  840. # str(self.ui.FIDProcComboBox.currentText()), self.ui.mplwidget, \
  841. # 1e-3 * self.ui.DeadTimeSpinBox.value( ), self.ui.plotImportCheckBox.isChecked() )) #, self))
  842. self.YamlNode.Import["GMR Header"] = self.headerstr
  843. self.YamlNode.Import["opened"] = datetime.datetime.now().isoformat()
  844. self.YamlNode.Import["pulse Type"] = str(self.RAWDataProc.pulseType)
  845. self.YamlNode.Import["stacks"] = self.procStacks.tolist()
  846. self.YamlNode.Import["data channels"] = self.dataChan.tolist()
  847. self.YamlNode.Import["reference channels"] = self.refChan.tolist()
  848. self.YamlNode.Import["pulse records"] = str(self.ui.FIDProcComboBox.currentText())
  849. self.YamlNode.Import["instrument dead time"] = (1e-3 * self.ui.DeadTimeSpinBox.value( ))
  850. self.Log ( )
  851. # should be already done
  852. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("updateProgress(int)"), self.updateProgressBar)
  853. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("enableDSP()"), self.enableDSP)
  854. # QtCore.QObject.connect(self.RAWDataProc, QtCore.SIGNAL("doneStatus()"), self.doneStatus)
  855. #self.ui.ProcessedBox.setEnabled(True)
  856. self.ui.lcdNumberFID1Length.setEnabled(1)
  857. self.ui.lcdNumberFID2Length.setEnabled(1)
  858. self.ui.lcdNumberResampFreq.setEnabled(1)
  859. self.ui.lcdTotalDeadTime.setEnabled(1)
  860. self.ui.lcdTotalDeadTime.display( self.ui.DeadTimeSpinBox.value( ) )
  861. #self.ui.lcdNumberFID1Length.display(0)
  862. #self.ui.lcdNumberFID2Length.display(0)
  863. #self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  864. self.mpl_toolbar = NavigationToolbar2QT(self.ui.mplwidget, self.ui.mplwidget)
  865. self.ui.mplwidget.draw()
  866. def Log(self):
  867. #for line in yaml.dump(self.YamlNode, default_flow_style=False):
  868. #for line in nlogText:
  869. # self.ui.logTextBrowser.append( line )
  870. # self.logText.append( line )
  871. self.ui.logTextBrowser.clear()
  872. self.ui.logTextBrowser.append( yaml.dump(self.YamlNode ))
  873. def disable(self):
  874. self.ui.inputRAWParametersBox.setEnabled(False)
  875. self.ui.BandPassBox.setEnabled(False)
  876. self.ui.downSampleGroupBox.setEnabled(False)
  877. self.ui.windowFilterGroupBox.setEnabled(False)
  878. self.ui.harmonicBox.setEnabled(False)
  879. # self.ui.despikeGroupBox.setEnabled(False)
  880. self.ui.adaptBox.setEnabled(False)
  881. self.ui.adaptFDBox.setEnabled(False)
  882. self.ui.qCalcGroupBox.setEnabled(False)
  883. self.ui.FDSmartStackGroupBox.setEnabled(False)
  884. self.ui.sumDataBox.setEnabled(False)
  885. self.ui.qdGroupBox.setEnabled(False)
  886. self.ui.gateBox.setEnabled(False)
  887. def enableAll(self):
  888. self.enableDSP()
  889. self.enableQC()
  890. def enableDSP(self):
  891. # Bandpass filter
  892. self.ui.BandPassBox.setEnabled(True)
  893. self.ui.BandPassBox.setChecked(True)
  894. self.ui.bandPassGO.setEnabled(False) # need to design first
  895. self.ui.plotBP.setEnabled(True)
  896. self.ui.plotBP.setChecked(True)
  897. # downsample
  898. self.ui.downSampleGroupBox.setEnabled(True)
  899. self.ui.downSampleGroupBox.setChecked(True)
  900. # window
  901. self.ui.windowFilterGroupBox.setEnabled(True)
  902. self.ui.windowFilterGroupBox.setChecked(True)
  903. # Despike
  904. # self.ui.despikeGroupBox.setEnabled(True)
  905. # self.ui.despikeGroupBox.setChecked(False)
  906. # Adaptive filtering
  907. self.ui.adaptBox.setEnabled(True)
  908. self.ui.adaptBox.setChecked(True)
  909. # FD Adaptive filtering
  910. self.ui.adaptFDBox.setEnabled(True)
  911. self.ui.adaptFDBox.setChecked(False)
  912. # Harmonic
  913. self.ui.harmonicBox.setEnabled(True)
  914. self.ui.harmonicBox.setChecked(True)
  915. self.LCDHarmonics()
  916. self.LCDHarmonics2()
  917. # sum group box
  918. try:
  919. if len(self.dataChan) > 1:
  920. self.ui.sumDataBox.setEnabled(True)
  921. self.ui.sumDataBox.setChecked(False)
  922. except:
  923. pass
  924. # Quadrature Detect
  925. self.ui.qdGroupBox.setEnabled(True)
  926. self.ui.qdGroupBox.setChecked(True)
  927. self.enableQC()
  928. def enableQC(self):
  929. # Q calc
  930. self.ui.qCalcGroupBox.setEnabled(True)
  931. self.ui.qCalcGroupBox.setChecked(True)
  932. # FD SmartStack
  933. self.ui.FDSmartStackGroupBox.setEnabled(True)
  934. self.ui.FDSmartStackGroupBox.setChecked(True)
  935. # Quadrature detect
  936. try:
  937. for pulse in self.RAWDataProc.DATADICT["PULSES"]:
  938. np.shape(self.RAWDataProc.DATADICT[pulse]["Q"])
  939. self.RAWDataProc.DATADICT["stack"]
  940. self.ui.qdGroupBox.setEnabled(True)
  941. self.ui.qdGroupBox.setChecked(True)
  942. except:
  943. self.ui.qdGroupBox.setEnabled(False)
  944. self.ui.qdGroupBox.setChecked(False)
  945. # Gating
  946. try:
  947. self.RAWDataProc.DATADICT["CA"]
  948. self.ui.gateBox.setEnabled(True)
  949. self.ui.gateBox.setChecked(True)
  950. except:
  951. self.ui.gateBox.setEnabled(False)
  952. self.ui.gateBox.setChecked(False)
  953. def despikeFilter(self):
  954. self.lock("despike filter")
  955. thread.start_new_thread(self.RAWDataProc.despike, \
  956. (self.ui.windowSpinBox.value(), \
  957. self.ui.thresholdSpinBox.value(), \
  958. str(self.ui.replComboBox.currentText()), \
  959. self.ui.rollOnSpinBox.value(), \
  960. self.ui.despikeInterpWinSpinBox.value(),
  961. self.ui.mplwidget))
  962. def calcQ(self):
  963. if "Calc Q" not in self.YamlNode.Stacking.keys():
  964. #print("In CalcQ", yaml.dump(self.YamlNode.Processing) )
  965. self.YamlNode.Stacking["Calc Q"] = True
  966. #print( yaml.dump(self.YamlNode.Processing) )
  967. self.Log()
  968. else:
  969. err_msg = "Q values have already been calculated"
  970. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  971. err_msg)
  972. return
  973. self.lock("pulse moment calculation")
  974. thread.start_new_thread(self.RAWDataProc.effectivePulseMoment, \
  975. (self.ui.CentralVSpinBox.value(), \
  976. self.ui.mplwidget))
  977. def harmonicModel(self):
  978. self.lock("harmonic noise modelling")
  979. Harm = OrderedDict()
  980. Harm["STEP"] = "Harmonic modelling"
  981. Harm["NF"] = str( self.ui.NHarmonicsFreqsSpin.value() )
  982. Harm["Segments"] = str( self.ui.NSegments.value() )
  983. Harm["Proc. ref."] = self.ui.harmRef.isChecked()
  984. if self.ui.searchAll.currentText() == "All":
  985. Harm["search"] = self.ui.searchAll.currentText()
  986. Search = False
  987. else:
  988. #Harm["search"] = self.ui.searchAll.currentText()
  989. Harm["search"] = str(self.ui.Nsearch.value())
  990. Search = self.ui.Nsearch.value()
  991. if self.ui.boundsCheck.isChecked():
  992. Harm["Bounds"] = str(self.ui.bounds.value())
  993. Bounds = self.ui.bounds.value()
  994. else:
  995. Harm["Bounds"] = self.ui.boundsCheck.isChecked()
  996. Bounds = 0
  997. Harm["f0K1"] = str( self.ui.f0K1Spin.value() )
  998. Harm["f0KN"] = str( self.ui.f0KNSpin.value() )
  999. Harm["f0Ks"] = str( self.ui.f0KsSpin.value() )
  1000. Harm["f0"] = str( self.ui.f0Spin.value() )
  1001. if self.ui.NHarmonicsFreqsSpin.value() > 1:
  1002. Harm["f1K1"] = str( self.ui.f1K1Spin.value() )
  1003. Harm["f1KN"] = str( self.ui.f1KNSpin.value() )
  1004. Harm["f1Ks"] = str( self.ui.f1KsSpin.value() )
  1005. Harm["f1"] = str( self.ui.f1Spin.value() )
  1006. self.YamlNode.Processing.append(Harm)
  1007. self.Log()
  1008. thread.start_new_thread(self.RAWDataProc.harmonicModel, \
  1009. ( \
  1010. self.ui.NHarmonicsFreqsSpin.value(), \
  1011. self.ui.f0Spin.value(), \
  1012. self.ui.f0K1Spin.value(), \
  1013. self.ui.f0KNSpin.value(), \
  1014. self.ui.f0KsSpin.value(), \
  1015. self.ui.NSegments.value(), \
  1016. self.ui.f1Spin.value(), \
  1017. self.ui.f1K1Spin.value(), \
  1018. self.ui.f1KNSpin.value(), \
  1019. self.ui.f1KsSpin.value(), \
  1020. Search, \
  1021. Bounds, \
  1022. self.ui.harmRef.isChecked(), \
  1023. self.ui.plotHarmonic.isChecked(), \
  1024. self.ui.mplwidget \
  1025. ) \
  1026. )
  1027. def FDSmartStack(self):
  1028. if "TD stack" not in self.YamlNode.Stacking.keys():
  1029. self.YamlNode.Stacking["TD stack"] = {}
  1030. self.YamlNode.Stacking["TD stack"]["outlier"] = str( self.ui.outlierTestCB.currentText() )
  1031. self.YamlNode.Stacking["TD stack"]["cutoff"] = str( self.ui.MADCutoff.value() )
  1032. self.Log()
  1033. else:
  1034. err_msg = "TD noise cancellation has already been applied!"
  1035. reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1036. err_msg)
  1037. return
  1038. self.lock("time-domain smart stack")
  1039. thread.start_new_thread(self.RAWDataProc.TDSmartStack, \
  1040. (str(self.ui.outlierTestCB.currentText()), \
  1041. self.ui.MADCutoff.value(),
  1042. self.ui.mplwidget))
  1043. def adaptFilter(self):
  1044. self.lock("TD noise cancellation filter")
  1045. # Log processing
  1046. Adapt = OrderedDict()
  1047. Adapt["STEP"] = "TD noise cancellation"
  1048. Adapt["n_Taps"] = str(self.ui.MTapsSpinBox.value())
  1049. Adapt["lambda"] = str(self.ui.adaptLambdaSpinBox.value())
  1050. Adapt["truncate"] = str(self.ui.adaptTruncateSpinBox.value())
  1051. Adapt["mu"] = str(self.ui.adaptMuSpinBox.value())
  1052. Adapt["PCA"] = str(self.ui.PCAComboBox.currentText())
  1053. self.YamlNode.Processing.append(Adapt)
  1054. self.Log( )
  1055. thread.start_new_thread(self.RAWDataProc.adaptiveFilter, \
  1056. (self.ui.MTapsSpinBox.value(), \
  1057. self.ui.adaptLambdaSpinBox.value(), \
  1058. self.ui.adaptTruncateSpinBox.value(), \
  1059. self.ui.adaptMuSpinBox.value(), \
  1060. str(self.ui.PCAComboBox.currentText()), \
  1061. self.ui.mplwidget))
  1062. def sumDataChans(self):
  1063. self.lock("Summing data channels")
  1064. Sum = OrderedDict()
  1065. Sum["STEP"] = "Channel sum"
  1066. self.YamlNode.Processing.append(Sum)
  1067. self.Log( )
  1068. self.dataChan = [self.dataChan[0]]
  1069. self.ui.sumDataBox.setEnabled(False)
  1070. thread.start_new_thread( self.RAWDataProc.sumData, ( self.ui.mplwidget, 7 ) )
  1071. def adaptFilterFD(self):
  1072. self.lock("FD noise cancellation filter")
  1073. thread.start_new_thread(self.RAWDataProc.adaptiveFilterFD, \
  1074. (str(self.ui.windowTypeComboBox.currentText()), \
  1075. self.ui.windowBandwidthSpinBox.value(), \
  1076. self.ui.CentralVSpinBox.value(), \
  1077. self.ui.mplwidget))
  1078. def bandPassFilter(self):
  1079. self.lock("bandpass filter")
  1080. # Log processing
  1081. Band = OrderedDict()
  1082. Band["STEP"] = "Bandpass filter"
  1083. Band["central_nu"] = str(self.ui.CentralVSpinBox.value())
  1084. Band["passband"] = str(self.ui.passBandSpinBox.value())
  1085. Band["stopband"] = str(self.ui.stopBandSpinBox.value())
  1086. Band["gpass"] = str(self.ui.gpassSpinBox.value())
  1087. Band["gstop"] = str(self.ui.gstopSpinBox.value())
  1088. Band["type"] = str(self.ui.fTypeComboBox.currentText())
  1089. self.YamlNode.Processing.append(Band)
  1090. self.Log( )
  1091. nv = self.ui.lcdTotalDeadTime.value( ) + self.ui.lcdNumberFTauDead.value()
  1092. self.ui.lcdTotalDeadTime.display( nv )
  1093. thread.start_new_thread(self.RAWDataProc.bandpassFilter, \
  1094. (self.ui.mplwidget, 0, self.ui.plotBP.isChecked() ))
  1095. def downsample(self):
  1096. self.lock("resampling")
  1097. # Log processing
  1098. Resample = OrderedDict()
  1099. Resample["STEP"] = "Resample"
  1100. Resample["downsample factor"] = str(self.ui.downSampleSpinBox.value())
  1101. Resample["truncate length"] = str(self.ui.truncateSpinBox.value())
  1102. self.YamlNode.Processing.append(Resample)
  1103. self.Log( )
  1104. thread.start_new_thread(self.RAWDataProc.downsample, \
  1105. (self.ui.truncateSpinBox.value(), \
  1106. self.ui.downSampleSpinBox.value(), \
  1107. self.ui.dsPlot.isChecked(), \
  1108. self.ui.mplwidget))
  1109. def quadDet(self):
  1110. method = ['trf','dogbox','lm'][int(self.ui.QDMethod.currentIndex())]
  1111. loss = ['linear','soft_l1','cauchy','huber'][int(self.ui.QDLoss.currentIndex())]
  1112. # allow overwrite of Quad Det.
  1113. self.YamlNode.Stacking["Quadrature detection"] = {}
  1114. self.YamlNode.Stacking["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1115. self.YamlNode.Stacking["Quadrature detection"]["method"] = method
  1116. self.YamlNode.Stacking["Quadrature detection"]["loss"] = loss
  1117. self.Log()
  1118. #if "Quadrature detection" not in self.YamlNode.Processing.keys():
  1119. # self.YamlNode.Processing["Quadrature detection"] = {}
  1120. # self.YamlNode.Processing["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1121. # self.Log()
  1122. #else:
  1123. # self.YamlNode.Processing["Quadrature detection"] = {}
  1124. # self.YamlNode.Processing["Quadrature detection"]["trim"] = str( self.ui.trimSpin.value() )
  1125. # self.Log()
  1126. #err_msg = "Quadrature detection has already been done!"
  1127. #reply =QtWidgets.QMessageBox.critical(self, 'Error',
  1128. # err_msg)
  1129. #return
  1130. self.lock("quadrature detection")
  1131. thread.start_new_thread(self.RAWDataProc.quadDet, \
  1132. (self.ui.trimSpin.value(), method, loss, self.ui.mplwidget))
  1133. self.ui.plotQD.setEnabled(True)
  1134. def plotQD(self):
  1135. self.lock("plot QD")
  1136. thread.start_new_thread(self.RAWDataProc.plotQuadDet, \
  1137. (self.ui.trimSpin.value(), int(self.ui.QDType.currentIndex()), self.ui.mplwidget))
  1138. def gateIntegrate(self):
  1139. if "Gate integrate" not in self.YamlNode.Stacking.keys():
  1140. self.YamlNode.Stacking["Gate integrate"] = {}
  1141. self.YamlNode.Stacking["Gate integrate"]["gpd"] = str(self.ui.GPDspinBox.value( ) )
  1142. self.Log()
  1143. self.lock("gate integration")
  1144. thread.start_new_thread(self.RAWDataProc.gateIntegrate, \
  1145. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), self.ui.mplwidget))
  1146. self.ui.actionExport_Preprocessed_Dataset.setEnabled(True)
  1147. self.ui.plotGI.setEnabled(True)
  1148. def plotGI(self):
  1149. self.lock("plot gate integrate")
  1150. thread.start_new_thread(self.RAWDataProc.plotGateIntegrate, \
  1151. (self.ui.GPDspinBox.value(), self.ui.trimSpin.value(), \
  1152. self.ui.QDType_2.currentIndex(), self.ui.mplwidget))
  1153. def designFilter(self):
  1154. [bord, fe] = self.RAWDataProc.designFilter( \
  1155. self.ui.CentralVSpinBox.value(), \
  1156. self.ui.passBandSpinBox.value(), \
  1157. self.ui.stopBandSpinBox.value(), \
  1158. self.ui.gpassSpinBox.value(), \
  1159. self.ui.gstopSpinBox.value(), \
  1160. str(self.ui.fTypeComboBox.currentText()),
  1161. self.ui.mplwidget
  1162. )
  1163. self.ui.lcdNumberFilterOrder.display(bord)
  1164. self.ui.lcdNumberFTauDead.display(1e3*fe)
  1165. self.ui.bandPassGO.setEnabled(1)
  1166. ################################################################
  1167. # Hack for MacOS to force refresh of group box and plot
  1168. # this has an undesirable effect that it causes the groupbox to 'jump' up
  1169. # TODO come up with a better solution
  1170. self.ui.mplwidget.hide()
  1171. self.ui.mplwidget.show()
  1172. self.ui.BandPassBox.hide()
  1173. self.ui.BandPassBox.show()
  1174. def windowFilter(self):
  1175. self.lock("window filter")
  1176. # Log processing
  1177. Window = OrderedDict()
  1178. Window["STEP"] = "Window filter"
  1179. Window["type"] = str(self.ui.windowTypeComboBox.currentText())
  1180. Window["width"] = str(self.ui.windowBandwidthSpinBox.value())
  1181. Window["centre"] = str(self.ui.CentralVSpinBox.value() )
  1182. Window["trim"] = str(self.ui.windowTrim.isChecked())
  1183. self.YamlNode.Processing.append(Window)
  1184. self.Log( )
  1185. if self.ui.windowTrim.isChecked():
  1186. nv = self.ui.lcdTotalDeadTime.value( ) + self.ui.lcdWinDead.value()
  1187. self.ui.lcdTotalDeadTime.display( nv )
  1188. thread.start_new_thread(self.RAWDataProc.windowFilter, \
  1189. (str(self.ui.windowTypeComboBox.currentText()), \
  1190. self.ui.windowBandwidthSpinBox.value(), \
  1191. self.ui.CentralVSpinBox.value(), \
  1192. self.ui.windowTrim.isChecked(), \
  1193. self.ui.mplwidget))
  1194. def designFDFilter(self):
  1195. mPulse = "None"
  1196. if u"Pulse 1" in self.RAWDataProc.DATADICT.keys():
  1197. mPulse = u"Pulse 1"
  1198. elif u"Pulse 2" in self.RAWDataProc.DATADICT.keys():
  1199. mPulse = u"Pulse 2"
  1200. a,b,c,d,dead,ndead = self.RAWDataProc.computeWindow( \
  1201. mPulse,
  1202. self.ui.windowBandwidthSpinBox.value(), \
  1203. self.ui.CentralVSpinBox.value(), \
  1204. str(self.ui.windowTypeComboBox.currentText()), \
  1205. self.ui.mplwidget )
  1206. self.ui.lcdWinDead.display(dead)
  1207. ################################################################
  1208. # Hack for MacOS to force refresh of group box and plot
  1209. # this has an undesirable effect that it causes the groupbox to 'jump' up
  1210. # TODO come up with a better solution
  1211. self.ui.mplwidget.hide()
  1212. self.ui.mplwidget.show()
  1213. self.ui.windowFilterGroupBox.hide()
  1214. self.ui.windowFilterGroupBox.show()
  1215. def updateProgressBar(self, percent):
  1216. self.ui.barProgress.setValue(percent)
  1217. def updateProc(self):
  1218. if str(self.ui.FIDProcComboBox.currentText()) == "Pulse 1":
  1219. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1220. elif str(self.ui.FIDProcComboBox.currentText()) == "Pulse 2":
  1221. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1222. else:
  1223. self.ui.lcdNumberFID1Length.display(self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 1"]["TIMES"][0])
  1224. self.ui.lcdNumberFID2Length.display(self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][-1]- self.RAWDataProc.DATADICT["Pulse 2"]["TIMES"][0])
  1225. self.ui.lcdNumberResampFreq.display( self.RAWDataProc.samp )
  1226. def doneStatus(self): # unlocks GUI
  1227. self.ui.statusbar.clearMessage ( )
  1228. self.ui.barProgress.hide()
  1229. self.updateProc()
  1230. self.enableAll()
  1231. def lock(self, string):
  1232. self.ui.statusbar.showMessage ( string )
  1233. self.ui.barProgress.show()
  1234. self.ui.barProgress.setValue(0)
  1235. self.disable()
  1236. def unlock(self):
  1237. self.ui.statusbar.clearMessage ( )
  1238. self.ui.barProgress.hide()
  1239. self.enableAll()
  1240. def done(self):
  1241. self.ui.statusbar.showMessage ( "" )
  1242. ################################################################
  1243. ################################################################
  1244. # Boiler plate main function
  1245. import pkg_resources
  1246. from pkg_resources import resource_string
  1247. import matplotlib.image as mpimg
  1248. import matplotlib.pyplot as plt
  1249. def main():
  1250. # splash screen logo
  1251. logo = pkg_resources.resource_filename(__name__, 'akvo.png')
  1252. logo2 = pkg_resources.resource_filename(__name__, 'akvo2.png')
  1253. qApp = QtWidgets.QApplication(sys.argv)
  1254. ssplash = True
  1255. if ssplash:
  1256. pixmap = QtGui.QPixmap(logo)
  1257. splash = QtWidgets.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint)
  1258. splash.show()
  1259. aw = ApplicationWindow()
  1260. img=mpimg.imread(logo)
  1261. for ax in [ aw.ui.mplwidget ]:
  1262. ax.fig.clear()
  1263. subplot = ax.fig.add_subplot(111)
  1264. #ax.fig.patch.set_facecolor( None )
  1265. #ax.fig.patch.set_alpha( .0 )
  1266. subplot.imshow(img)
  1267. subplot.xaxis.set_major_locator(plt.NullLocator())
  1268. subplot.yaxis.set_major_locator(plt.NullLocator())
  1269. ax.draw()
  1270. if ssplash:
  1271. splash.showMessage("Loading modules")
  1272. splash.finish(aw)
  1273. #time.sleep(1)
  1274. aw.setWindowTitle("Akvo v"+str(version))
  1275. aw.show()
  1276. qApp.setWindowIcon(QtGui.QIcon(logo2))
  1277. sys.exit(qApp.exec_())
  1278. if __name__ == "__main__":
  1279. main()