Commit 16751ee9 authored by Hackmet's avatar Hackmet

Added database support,

several bugfixes
parent 86522ed2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 31 10:07:45 2018
@author: brandt
"""
"""
GEPARD - Gepard-Enabled PARticle Detection
Copyright (C) 2018 Lars Bittrich and Josef Brandt, Leibniz-Institut für
......@@ -41,6 +35,7 @@ from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as Navigatio
import pandas as pd
from analysis.loadresults import LoadWITecResults
from analysis.editParticles import ParticleEditor
from analysis.database import DataBaseWindow
try:
from analysis.sqlexport import SQLExport
sqlEnabled = True
......@@ -48,19 +43,22 @@ except:
sqlEnabled = False
class ParticleAnalysis(QtWidgets.QWidget):
class ParticleAnalysis(QtWidgets.QMainWindow):
def __init__(self, parent):
super(ParticleAnalysis, self).__init__()
self.setGeometry(100, 100, 1680, 1050)
self.setWindowTitle('Results of polymer analysis')
self.layout = QtWidgets.QHBoxLayout()
self.setLayout(self.layout)
self.widget = QtWidgets.QWidget()
self.widget.setLayout(self.layout)
self.setCentralWidget(self.widget)
self.parent = parent
if self.parent is not None:
self.config = self.parent.dataset.resultParams
self.editor = ParticleEditor(self)
self.expWin = None
self.spectraResults = None #entire List of all spectra assignments
self.additiveResults = None #entire List of all additives
......@@ -98,8 +96,7 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.sizeHistogramCanvas.figure.subplots_adjust(left=0.1, top=0.93, bottom=0.15, right=0.995)
histNavigation = NavigationToolbar(self.sizeHistogramCanvas, self)
histNavigation.setOrientation(QtCore.Qt.Vertical)
histNavigation.setMinimumWidth(50)
histNavigation.setMaximumWidth(50)
histNavigation.setFixedWidth(50)
sizeHistLayout.addWidget(histNavigation)
sizeHistLayout.addWidget(self.sizeHistogramCanvas)
sizeHistGroup.setLayout(sizeHistLayout)
......@@ -109,11 +106,11 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.specCanvas = FigureCanvas(Figure())
self.spec_ax = self.specCanvas.figure.subplots()
self.spec_ax.axis("off")
self.specCanvas.figure.subplots_adjust(left=0.1, top=0.93, bottom=0.15, right=0.995)
self.ref_ax = self.spec_ax.twinx()
self.specCanvas.figure.subplots_adjust(left=0.1, top=0.93, bottom=0.15, right=0.9)
specNavigation = NavigationToolbar(self.specCanvas, self)
specNavigation.setOrientation(QtCore.Qt.Vertical)
specNavigation.setMinimumWidth(50)
specNavigation.setMaximumWidth(50)
specNavigation.setFixedWidth(50)
specLayout.addWidget(specNavigation)
specLayout.addWidget(self.specCanvas)
......@@ -145,42 +142,6 @@ class ParticleAnalysis(QtWidgets.QWidget):
spinbox.setSingleStep(1)
spinbox.setValue(1)
self.overlayGroup = QtWidgets.QGroupBox('Color Overlay')
self.overlayLayout = QtWidgets.QHBoxLayout()
self.noOverlayBtn = QtWidgets.QRadioButton('None')
self.selOverlayBtn = QtWidgets.QRadioButton('Selected')
self.fullOverlayBtn = QtWidgets.QRadioButton('Full')
for index, button in enumerate([self.noOverlayBtn, self.selOverlayBtn, self.fullOverlayBtn]):
if index == 2:
button.setChecked(True)
else:
button.setChecked(False)
button.released.connect(self.createPolymerOverlay)
button.released.connect(self.updateHistogram)
self.overlayLayout.addWidget(button)
self.seedBtn = QtWidgets.QPushButton('Set Color Seed')
self.seedBtn.released.connect(self.updateColorSeed)
self.overlayLayout.addWidget(self.seedBtn)
self.hideLabelBtn = QtWidgets.QCheckBox('Hide Polymer Numbers')
self.hideLabelBtn.stateChanged.connect(self.show_hide_labels)
self.hideLabelBtn.setChecked(False)
# self.hideLabelBtn.setChecked(True) #change twice in order to run the connected function...
self.overlayLayout.addWidget(self.hideLabelBtn)
self.transpBtn = QtWidgets.QCheckBox('Transparent')
self.transpBtn.setChecked(False)
self.transpBtn.stateChanged.connect(self.createPolymerOverlay)
self.overlayLayout.addWidget(self.transpBtn)
self.darkenBtn = QtWidgets.QCheckBox('Darken Image')
self.darkenBtn.setChecked(False)
self.darkenBtn.stateChanged.connect(self.darkenBackground)
self.overlayLayout.addWidget(self.darkenBtn)
self.overlayGroup.setLayout(self.overlayLayout)
navigationLayout.addWidget(QtWidgets.QLabel('Select Polymer Type:'))
navigationLayout.addWidget(self.polymerComboBox)
navigationLayout.addStretch()
......@@ -192,25 +153,39 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.navigationGroup.setLayout(navigationLayout)
referenceGroup = QtWidgets.QGroupBox('Reference Spectra')
referenceLayout = QtWidgets.QHBoxLayout()
self.refSelector = QtWidgets.QComboBox()
self.refSelector.setDisabled(True)
self.dbWin = DataBaseWindow(self)
self.dbWin.selectDataBase(refreshParent=True) #this includes updating the refSelector
self.refSelector.currentIndexChanged.connect(self.updateSpecPlot)
referenceLayout.addWidget(QtWidgets.QLabel('Select Reference'))
referenceLayout.addWidget(self.refSelector)
referenceGroup.setLayout(referenceLayout)
topLayout = QtWidgets.QHBoxLayout()
topLayout.addWidget(self.navigationGroup)
topLayout.addWidget(self.overlayGroup)
topLayout.addWidget(referenceGroup)
topLayout.addStretch()
viewLayout.addLayout(topLayout)
viewLayout.addWidget(splitter2)
viewLayout.setStretch(1, 1)
reloadGroup = QtWidgets.QGroupBox('Reload Results from:')
reloadLayout = QtWidgets.QVBoxLayout()
self.reloadWITec = QtWidgets.QRadioButton('WITec True Match')
self.reloadWITec.setChecked(True)
self.reloadTxt = QtWidgets.QRadioButton('Ordered text file')
reloadBtn = QtWidgets.QPushButton('reload Results')
reloadBtn.clicked.connect(self.importResults)
reloadLayout.addWidget(self.reloadWITec)
reloadLayout.addWidget(self.reloadTxt)
reloadLayout.addWidget(reloadBtn)
reloadGroup.setLayout(reloadLayout)
# reloadGroup = QtWidgets.QGroupBox('Reload Results from:')
# reloadLayout = QtWidgets.QVBoxLayout()
# self.reloadWITec = QtWidgets.QRadioButton('WITec True Match')
# self.reloadWITec.setChecked(True)
# self.reloadTxt = QtWidgets.QRadioButton('Ordered text file')
# reloadBtn = QtWidgets.QPushButton('reload Results')
# reloadBtn.clicked.connect(self.importResults)
# reloadLayout.addWidget(self.reloadWITec)
# reloadLayout.addWidget(self.reloadTxt)
# reloadLayout.addWidget(reloadBtn)
# reloadGroup.setLayout(reloadLayout)
self.optionsGroup = QtWidgets.QGroupBox('Further Options')
optionsLayout = QtWidgets.QFormLayout()
......@@ -267,14 +242,9 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.layout_SArea.addWidget(self.resultCheckBoxes)
# self.layout_SArea.addStretch(1)
self.exportbtn= QtWidgets.QPushButton('Export Results')
self.exportbtn.clicked.connect(self.exportData)
self.exportbtn.setDisabled(True)
self.menuLayout.addWidget(reloadGroup)
# self.menuLayout.addWidget(reloadGroup)
self.menuLayout.addWidget(self.optionsGroup)
self.menuLayout.addWidget(self.resultScrollarea)
self.menuLayout.addWidget(self.exportbtn)
self.layout.addLayout(self.menuLayout)
self.layout.addLayout(viewLayout)
......@@ -285,16 +255,106 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.hqiSpinBox.setValue(self.config['minHQI'])
self.compHqiSpinBox.setValue(self.config['compHQI'])
self.createActions()
self.createMenus()
self.updateData()
def createActions(self):
self.loadTrueMatchAct = QtWidgets.QAction("Load &TrueMatch Results", self)
self.loadTrueMatchAct.triggered.connect(self.importTrueMatchResults)
self.loadTextFileAct = QtWidgets.QAction("Load &ordered Text File", self)
self.loadTextFileAct.setDisabled(True)
self.noOverlayAct = QtWidgets.QAction("&No Overlay", self)
self.selOverlayAct = QtWidgets.QAction("&Selected Overlay", self)
self.fullOverlayAct = QtWidgets.QAction("&Full Overlay", self)
self.transpAct = QtWidgets.QAction("&Transparent Overlay")
self.transpAct.triggered.connect(self.createPolymerOverlay)
self.hideLabelAct = QtWidgets.QAction('&Hide Polymer Numbers', self)
self.hideLabelAct.triggered.connect(self.show_hide_labels)
self.darkenAct = QtWidgets.QAction("&Darken Image", self)
self.darkenAct.triggered.connect(self.darkenBackground)
for act in [self.noOverlayAct, self.selOverlayAct, self.fullOverlayAct, self.hideLabelAct, self.transpAct, self.darkenAct]:
act.setCheckable(True)
self.fullOverlayAct.setChecked(True)
self.seedAct = QtWidgets.QAction("&Set Color Seed", self)
self.seedAct.triggered.connect(self.updateColorSeed)
self.databaseAct = QtWidgets.QAction("&ManageDatabase", self)
self.databaseAct.triggered.connect(self.launchDBManager)
self.expExcelAct= QtWidgets.QAction("Export &Excel List", self)
self.expExcelAct.setDisabled(True)
self.expExcelAct.triggered.connect(self.exportToExcel)
self.expSQLAct = QtWidgets.QAction("Export to &SQL Database", self)
self.expSQLAct.setDisabled(True)
self.expSQLAct.triggered.connect(self.exportToSQL)
def createMenus(self):
self.importMenu = QtWidgets.QMenu("&Import Results")
self.importMenu.addActions([self.loadTrueMatchAct, self.loadTextFileAct])
self.dispMenu = QtWidgets.QMenu("&Display", self)
self.overlayActGroup = QtWidgets.QActionGroup(self.dispMenu)
self.overlayActGroup.setExclusive(True)
self.overlayActGroup.triggered.connect(self.createPolymerOverlay)
self.overlayActGroup.triggered.connect(self.updateHistogram)
for act in [self.noOverlayAct, self.selOverlayAct, self.fullOverlayAct]:
self.dispMenu.addAction(act)
self.overlayActGroup.addAction(act)
self.dispMenu.addSeparator()
self.dispMenu.addActions([self.transpAct, self.hideLabelAct, self.darkenAct, self.seedAct])
self.refMenu = QtWidgets.QMenu("&References")
self.refMenu.addAction(self.databaseAct)
self.exportMenu = QtWidgets.QMenu("&Export", self)
self.exportMenu.addAction(self.expExcelAct)
self.exportMenu.addAction(self.expSQLAct)
self.menuBar().addMenu(self.importMenu)
self.menuBar().addMenu(self.dispMenu)
self.menuBar().addMenu(self.refMenu)
self.menuBar().addMenu(self.exportMenu)
def launchDBManager(self):
if self.dbWin.isHidden():
self.dbWin.show()
def populateRefSelector(self):
#delete all present entries:
self.refSelector.clear()
if self.dbWin.activeDatabase is None:
self.refSelector.setDisabled(True)
else:
self.refSelector.addItems(self.dbWin.activeDatabase.spectraNames)
self.refSelector.setDisabled(False)
def loadSpectra(self, fname):
import time
t0 = time.time()
specfilename = self.parent.dataset.fname.split('.pkl')[0] + '_spectra.npy'
if os.path.exists(specfilename):
return np.load(specfilename)
else:
try:
specs = np.loadtxt(fname)
#if spectra are already in correct format (WITec, first column: wavenumbers, other columns, intensities),
#we take them, otherwise we have to convert from Renishaw export format...
if len(np.unique(specs[:, 0])) == len(specs[:, 0]): #--> only unique numbers -> this is the wavenumber column, we have the witec format
return specs
else:
if not len(np.unique(specs[:, 0])) == len(specs[:, 0]): #--> only unique numbers -> this is the wavenumber column, we have the witec format
#Renishaw Convert
#columns 0 and 1 are x and y coordinates. We dont need them...
startWavenumber = specs[0, 2]
startIndices = np.where(specs[:, 2] == startWavenumber)[0]
......@@ -305,8 +365,15 @@ class ParticleAnalysis(QtWidgets.QWidget):
spectra[:, i+1] = specs[startIndices[i]:startIndices[i+1], 3]
#aaand the last spectrum:
spectra[:, -1] = specs[startIndices[-1]:, 3]
return np.flip(spectra, 0) #Renishaw goes from highest to lowest wavenumber, out of whatever reason...
specs = np.flip(spectra, 0) #Renishaw goes from highest to lowest wavenumber, out of whatever reason...
#write spectra to binary file, that makes reloading them in future significantly faster
np.save(specfilename, specs)
print('loading specs:', time.time()-t0)
return specs
except:
raise
return None
def updateData(self):
......@@ -332,7 +399,7 @@ class ParticleAnalysis(QtWidgets.QWidget):
QtWidgets.QMessageBox.critical(self, 'ERROR!', 'spectra file could not be opened with np.loadtxt...')
return
self.parent.dataset.spectraPath = fname
self.spec_ax.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
# self.spec_ax.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
self.specCanvas.draw()
####fake data!!!
......@@ -376,12 +443,9 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.updateBtn.clicked.connect(self.formatResults)
self.formatResults()
def importResults(self):
if self.reloadWITec.isChecked():
def importTrueMatchResults(self):
self.importWindow = LoadWITecResults(self)
self.importWindow.show()
elif self.reloadTxt.isChecked():
QtWidgets.QMessageBox.about(self, 'sorry...', 'Ordered Text import not yet implemented...')
def getAdditivePlot(self, event):
clickedindex = int(np.round(event.xdata))
......@@ -505,7 +569,9 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.typeHistogramCanvas.setCursor(QtGui.QCursor(QtCore.Qt.WhatsThisCursor))
self.typeHistogramCanvas.mpl_connect('button_press_event', self.getAdditivePlot)
self.exportbtn.setDisabled(False)
self.expExcelAct.setDisabled(False)
if sqlEnabled:
self.expSQLAct.setDisabled(False)
self.navigationGroup.setEnabled(True)
self.polymerComboBox.currentIndexChanged.disconnect()
......@@ -519,19 +585,26 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.displayNewPolymerType(resetCurrentIndex=False)
else:
self.displayNewPolymerType()
self.updateHistogram()
self.createPolymerOverlay()
def exportData(self):
if self.expWindow is None:
self.expWindow = ExportDialog(self)
self.expWindow.show()
else:
self.expWindow.__init__(self)
self.expWindow.show()
def updatePolymerSpectrum(self, centerOn=True, highlightContour=True):
def exportToExcel(self):
if self.expWin is not None:
self.expWin.close()
self.expWin.destroy()
self.expWin = ExpExcelDialog(self)
self.expWin.show()
def exportToSQL(self):
if self.expWin is not None:
self.expWin.close()
self.expWin.destroy()
self.expWin = SQLExport(self)
self.expWin.show()
def updateSpecPlot(self, centerOn=True, highlightContour=True):
#draw Sample Spectrum
specIndex = self.currentSpectrumIndex
self.spec_ax.axis("on")
self.spec_ax.clear()
......@@ -541,6 +614,29 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.spec_ax.set_ylabel('Counts', fontsize = 15)
self.spec_ax.set_title('ScanPoint Number {}, Size = {} µm'.format(specIndex+1, np.round(self.particlestats[self.currentParticleIndex][2], 1)))
self.spec_ax.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
wavenumber_diff = list(self.spectra[:, 0]-100)
y_start = wavenumber_diff.index(min(wavenumber_diff))
y_min = min(self.spectra[y_start:, specIndex+1])
y_max = max(self.spectra[y_start:, specIndex+1])
self.spec_ax.set_ybound(0.9*y_min, 1.1*y_max)
#draw Reference
self.ref_ax.clear()
if self.refSelector.isEnabled() and self.refSelector.currentText() != '':
self.ref_ax.tick_params(axis='both', which='both', labelsize=15)
refID = self.dbWin.activeDatabase.spectraNames.index(self.refSelector.currentText())
ref = self.dbWin.activeDatabase.spectra[refID]
self.ref_ax.plot(ref[:, 0], ref[:, 1], color = 'r')
self.ref_ax.set_ylabel('Ref. Intensity', fontsize = 15, color = 'r')
self.ref_ax.tick_params('y', colors = 'r')
self.ref_ax.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
# wavenumber_diff = list(ref[:, 0]-100)
# y_start = wavenumber_diff.index(min(wavenumber_diff))
# y_min = min(ref[y_start:, specIndex+1])
# y_max = max(ref[y_start:, specIndex+1])
self.spec_ax.figure.canvas.draw()
self.parent.centerOnRamanIndex(specIndex, centerOn=centerOn, highlightContour=highlightContour)
self.parent.highLightRamanIndex(specIndex)
......@@ -555,11 +651,11 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.spectrumSelector.setMaximum(len(self.particles2spectra[self.currentParticleIndex]))
self.currentParticleIndex = self.indices[self.polymerIndex][self.particleSelector.value()-1]
self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
self.updatePolymerSpectrum(centerOn=True)
self.updateSpecPlot(centerOn=True)
else:
self.currentParticleIndex = self.indices[self.polymerIndex][self.particleSelector.value()-1]
self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
self.updatePolymerSpectrum(centerOn=False)
self.updateSpecPlot(centerOn=False)
def selectParticle(self, resetSpectrumCount=True):
if self.particles2spectra is not None:
......@@ -568,14 +664,14 @@ class ParticleAnalysis(QtWidgets.QWidget):
if resetSpectrumCount:
self.spectrumSelector.setValue(1)
self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
self.updatePolymerSpectrum()
self.updateSpecPlot()
else:
print('no spectrum assignment found...')
def selectSpectrum(self):
if self.particles2spectra is not None:
self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
self.updatePolymerSpectrum()
self.updateSpecPlot()
def updateHistogram(self):
self.sizeHist_ax.clear()
......@@ -586,7 +682,7 @@ class ParticleAnalysis(QtWidgets.QWidget):
#draw the general histogram
colorList = []
if self.selOverlayBtn.isChecked():
if self.selOverlayAct.isChecked():
abundancyList = []
for index, checkbox in enumerate(self.polymerCheckBoxes):
if checkbox.isChecked():
......@@ -608,7 +704,7 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.histPlotTextLabels = []
y_label_position = 0
for index, i in enumerate(self.typehistogram):
if not self.selOverlayBtn.isChecked() or self.polymerCheckBoxes[index].isChecked():
if not self.selOverlayAct.isChecked() or self.polymerCheckBoxes[index].isChecked():
if self.sorted_additives is None:
numads = ''
else:
......@@ -698,9 +794,9 @@ class ParticleAnalysis(QtWidgets.QWidget):
def darkenBackground(self):
self.parent.darkenPixmap = self.darkenBtn.isChecked()
self.parent.darkenPixmap = self.darkenAct.isChecked()
if self.darkenBtn.isChecked():
if self.darkenAct.isChecked():
self.parent.scene().setBackgroundBrush(QtGui.QColor(5, 5, 5))
self.parent.item.setOpacity(0.2)
else:
......@@ -731,22 +827,20 @@ class ParticleAnalysis(QtWidgets.QWidget):
return color
def createPolymerOverlay(self):
if not self.noOverlayBtn.isChecked() and self.indices is not None:
if not self.noOverlayAct.isChecked() and self.indices is not None:
if len(self.indices) > 0:
# ramansortindices = self.parent.dataset.ramanscansortindex
alpha = (128 if self.transpBtn.isChecked() else 255)
alpha = (128 if self.transpAct.isChecked() else 255)
#get colors for each polymer type
colorList = [QtGui.QColor(255, 255, 255, alpha=50)]*len(self.particleResults)
legendItems = []
for index, indexList in enumerate(self.indices):
if self.fullOverlayBtn.isChecked() or (self.selOverlayBtn.isChecked() and self.polymerCheckBoxes[index].isChecked()):
if self.fullOverlayAct.isChecked() or (self.selOverlayAct.isChecked() and self.polymerCheckBoxes[index].isChecked()):
color = self.getColorFromName(self.uniquePolymers[index], base255=True)
color = QtGui.QColor(color[0], color[1], color[2], alpha=alpha)
legendItems.append((self.uniquePolymers[index], color))
for i in indexList:
# colorList[ramansortindices[i]] = color
colorList[i] = color
self.parent.contouritem.colorList = colorList
......@@ -764,7 +858,7 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.parent.imparent.legend.hide()
def show_hide_labels(self):
hidden = self.hideLabelBtn.isChecked()
hidden = self.hideLabelAct.isChecked()
for scanIndicator in self.parent.ramanscanitems:
scanIndicator.hidden = hidden
scanIndicator.update()
......@@ -777,22 +871,21 @@ class ParticleAnalysis(QtWidgets.QWidget):
self.parent.dataset.resultParams = {'minHQI': self.hqiSpinBox.value(),
'compHQI': self.compHqiSpinBox.value()}
# 'dispResults': self.dispResultSpinBox.value()}
self.parent.dataset.save()
print('saved dataset')
def closeEvent(self, event):
for window in [self.expWindow, self.additivePlot, self.importWindow]:
for window in [self.expWindow, self.additivePlot, self.importWindow, self.dbWin]:
try: window.close()
except: pass
self.saveAnalysisResults()
event.accept()
class ExportDialog(QtWidgets.QWidget):
class ExpExcelDialog(QtWidgets.QWidget):
def __init__(self, parent):
super(ExportDialog, self).__init__()
super(ExpExcelDialog, self).__init__()
self.setWindowTitle('Export Options')
self.setGeometry(200,200, 300, 300)
......@@ -843,22 +936,22 @@ class ExportDialog(QtWidgets.QWidget):
self.layout.addWidget(excelgroup)
sqlGroup = QtWidgets.QGroupBox('Export to SQL')
sqlLayout = QtWidgets.QVBoxLayout()
self.sqlbtn = QtWidgets.QPushButton('Export to SQL Database')
self.sqlbtn.resize(self.sqlbtn.sizeHint())
if sqlEnabled:
self.sqlbtn.clicked.connect(self.toSQL)
else:
self.sqlbtn.setDisabled(True)
self.sqlExport = None
sqlLayout.addWidget(self.sqlbtn)
sqlGroup.setLayout(sqlLayout)
self.layout.addWidget(sqlGroup)
# sqlGroup = QtWidgets.QGroupBox('Export to SQL')
# sqlLayout = QtWidgets.QVBoxLayout()
#
# self.sqlbtn = QtWidgets.QPushButton('Export to SQL Database')
# self.sqlbtn.resize(self.sqlbtn.sizeHint())
# if sqlEnabled:
# self.sqlbtn.clicked.connect(self.toSQL)
# else:
# self.sqlbtn.setDisabled(True)
#
# self.sqlExport = None
#
# sqlLayout.addWidget(self.sqlbtn)
# sqlGroup.setLayout(sqlLayout)
#
# self.layout.addWidget(sqlGroup)
self.show()
def toExcel(self):
......@@ -960,10 +1053,6 @@ class ExportDialog(QtWidgets.QWidget):
report.to_excel(writer, sheet_name = 'Particle Statistics', header = False, index = False)
QtWidgets.QMessageBox.about(self, 'Done!', 'Particle Data exported')
def toSQL(self):
self.sqlExport = SQLExport(self.parent)
self.sqlExport.show()
def closeEvent(self, event):
if self.sqlExport is not None:
self.sqlExport.close()
......
# -*- coding: utf-8 -*-
"""
GEPARD - Gepard-Enabled PARticle Detection
Copyright (C) 2018 Lars Bittrich and Josef Brandt, Leibniz-Institut für
Polymerforschung Dresden e. V. <bittrich-lars@ipfdd.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program, see COPYING.
If not, see <https://www.gnu.org/licenses/>.
"""
from PyQt5 import QtWidgets, QtCore
import numpy as np
import sys
import dill
import os
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import functools
from scipy.linalg import solveh_banded
from pathlib import Path
class DataBaseWindow(QtWidgets.QMainWindow):
def __init__(self, parent):
super(DataBaseWindow, self).__init__()
self.parent = parent
self.path = os.path.join(Path.home(), 'gepard', 'databases')
self.importPath = self.path
if not os.path.exists(self.path):
os.mkdir(self.path)
self.activeDatabase = None
self.activeSpectrum = None
self.activeSpectrumName = None
self.activeSpectrumIndex = None
self.databases = []
self.setWindowTitle('Edit Database')
self.setGeometry(200, 200, 1280, 720)
self.widget = QtWidgets.QWidget()
self.setCentralWidget(self.widget)
self.layout = QtWidgets.QGridLayout()
self.widget.setLayout(self.layout)
groupLayout = QtWidgets.QVBoxLayout()
self.db_selector = QtWidgets.QComboBox()
self.db_selector.currentIndexChanged.connect(self.selectDataBase)
self.databases = self.getDatabases()
self.updateDBSelectorList()
self.saveBtn = QtWidgets.QPushButton('Save databases')
self.saveBtn.clicked.connect(self.save)
groupLayout.addWidget(QtWidgets.QLabel('Select Active Database:'))
groupLayout.addWidget(self.db_selector)
groupLayout.addWidget(self.saveBtn)
groupBox = QtWidgets.QGroupBox()
groupBox.setLayout(groupLayout)
groupBox.setMaximumWidth(250)
self.layout.addWidget(groupBox, 1, 0)
self.modifyGroup = QtWidgets.QGroupBox('Modify Spectra')
modifyLayout = QtWidgets.QVBoxLayout()
self.modifyGroup.setDisabled(True)
self.blCorrectBtn = QtWidgets.QPushButton('Baseline Correct')
self.blCorrectBtn.clicked.connect(self.baselineCorrect)
self.cropBtn = QtWidgets.QPushButton('Crop Spectra')
self.cropBtn.clicked.connect(self.crop)
self.normalizeBtn = QtWidgets.QPushButton('Normalize')
self.normalizeBtn.clicked.connect(self.normalize)
self.resetBtn = QtWidgets.QPushButton('Restore Original Spectra')
self.resetBtn.clicked.connect(self.resetSpectra)
modifyLayout.addWidget(self.cropBtn)
modifyLayout.addWidget(self.blCorrectBtn)
modifyLayout.addWidget(self.normalizeBtn)
modifyLayout.addStretch()
modifyLayout.addWidget(self.resetBtn)
self.modifyGroup.setLayout(modifyLayout)
self.layout.addWidget(self.modifyGroup, 2, 0)
self.createActions()
self.createMenus()
self.updateDBInspector()
if self.parent is None:
self.show()
def createActions(self):
self.newDBAct = QtWidgets.QAction('Create &New Database', self)
self.newDBAct.triggered.connect(self.createNewDB)
self.importWITecAct = QtWidgets.QAction('Import &WITec Spectrum', self)
self.importWITecAct.triggered.connect(self.addWITecSpectra)
self.importReniAct = QtWidgets.QAction('Import &Renishaw Spectrum', self)
self.importReniAct.triggered.connect(self.addReniSpectra)
self.importReniAct.setDisabled(True)
def createMenus(self):
self.toolsMenu = QtWidgets.QMenu("&Tools", self)
self.importMenu = QtWidgets.QMenu("&ImportSpectra", self)
self.importMenu.addAction(self.importWITecAct)
self.importMenu.addAction(self.importReniAct)
self.toolsMenu.addAction(self.newDBAct)
self.toolsMenu.addSeparator()
self.toolsMenu.addMenu(self.importMenu)
self.menuBar().addMenu(self.toolsMenu)
def getDatabases(self):
dbInPath = [file for file in os.listdir(self.path) if file.endswith('.db')]
databases = []
for db in dbInPath:
with open(os.path.join(self.path, db), 'rb') as f:
databases.append(dill.load(f))
return databases
def createNewDB(self):
text, okPressed = QtWidgets.QInputDialog.getText(self, 'Name?', 'Name:', QtWidgets.QLineEdit.Normal, 'NewDatabase')
if okPressed and text != '':
#is there already a db with that name?
db_exists = False
for db in self.databases: