Commit 65d17844 authored by Hackmet's avatar Hackmet

Several Bugfixes

parent 16751ee9
......@@ -63,14 +63,14 @@ class Legend(QtWidgets.QMdiSubWindow):
font.setPixelSize(fontSize)
fm = QtGui.QFontMetrics(font)
pixelwidth = fm.width(text)
width, height = pixelwidth + tileSize + 3*spacer, numEntries * (tileSize+1*spacer) + 2*spacer
width, height = pixelwidth + tileSize + 4*spacer, numEntries * (fontSize+1*spacer) + spacer
return width, height
fontSize, tileSize, spacer = self.fontSize, self.tileSize, self.spacer
longestEntry = max([i[0] for i in self.items], key=len)
width, height = getSize(fontSize, longestEntry, tileSize, spacer)
#scale smaller, if necessary
# scale smaller, if necessary
if height > 1024:
factor = 1024/height
#prevent text getting tooo small:
......
......@@ -174,18 +174,6 @@ class ParticleAnalysis(QtWidgets.QMainWindow):
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)
self.optionsGroup = QtWidgets.QGroupBox('Further Options')
optionsLayout = QtWidgets.QFormLayout()
......@@ -338,6 +326,7 @@ class ParticleAnalysis(QtWidgets.QMainWindow):
if self.dbWin.activeDatabase is None:
self.refSelector.setDisabled(True)
else:
self.refSelector.addItem('')
self.refSelector.addItems(self.dbWin.activeDatabase.spectraNames)
self.refSelector.setDisabled(False)
......@@ -373,10 +362,10 @@ class ParticleAnalysis(QtWidgets.QMainWindow):
return specs
except:
raise
return None
def updateData(self):
print('updating data from', self.parent.dataset.name)
self.spectraResults = self.parent.dataset.results['polymers']
self.additiveResults = self.parent.dataset.results['additives']
self.hqis = self.parent.dataset.results['hqis']
......@@ -399,13 +388,8 @@ class ParticleAnalysis(QtWidgets.QMainWindow):
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.specCanvas.draw()
####fake data!!!
# if self.spectraResults is None:
# self.spectraResults = ['empty']*(self.spectra.shape[1]-1)
# self.hqis = [100]*(self.spectra.shape[1]-1)
self.loadParticleData()
......@@ -430,10 +414,9 @@ class ParticleAnalysis(QtWidgets.QMainWindow):
#check, if dataset already contains results. Otherwise load them...
if self.spectraResults is None or (len(self.spectraResults) != len(sortindices)):
self.show()
# QtWidgets.QMessageBox.about(self, 'Info', 'No (or inconsistent) spectra results found, please run import dialog.')
answer = QtWidgets.QMessageBox.question(self, 'Warning', 'No (or inconsistent) spectra results found, please run import dialog.\nPress OK to import or cancel to set to empty.', QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
if answer == QtWidgets.QMessageBox.Ok:
self.importResults()
self.importTrueMatchResults()
elif answer == QtWidgets.QMessageBox.Cancel:
self.spectraResults = ['empty']*(self.spectra.shape[1]-1)
self.hqis = [100]*(self.spectra.shape[1]-1)
......@@ -879,9 +862,9 @@ class ParticleAnalysis(QtWidgets.QMainWindow):
for window in [self.expWindow, self.additivePlot, self.importWindow, self.dbWin]:
try: window.close()
except: pass
self.saveAnalysisResults()
self.parent.imparent.particelAnalysisAct.setChecked(False)
event.accept()
class ExpExcelDialog(QtWidgets.QWidget):
def __init__(self, parent):
......@@ -1054,8 +1037,8 @@ class ExpExcelDialog(QtWidgets.QWidget):
QtWidgets.QMessageBox.about(self, 'Done!', 'Particle Data exported')
def closeEvent(self, event):
if self.sqlExport is not None:
self.sqlExport.close()
if self.expWin is not None:
self.expWin.close()
event.accept()
......
......@@ -143,8 +143,7 @@ class DataBaseWindow(QtWidgets.QMainWindow):
self.databases.append(Database(text))
self.activeDatabase = self.databases[-1]
self.updateDBSelectorList()
def addWITecSpectra(self):
fnames = QtWidgets.QFileDialog.getOpenFileNames(self, "Select Spectrum File", self.importPath, "*.txt")[0]
if fnames:
......@@ -170,6 +169,7 @@ class DataBaseWindow(QtWidgets.QMainWindow):
self.includeSpectrum(addSpectrum, specName)
self.updateDBInspector()
self.parent.populateRefSelector()
def addReniSpectra(self):
pass
......@@ -330,15 +330,17 @@ class DataBaseWindow(QtWidgets.QMainWindow):
self.db_selector.setCurrentText(self.activeDatabase.title)
def selectDataBase(self, refreshParent=False):
self.activeDatabaseIndex = self.db_selector.currentIndex()
self.activeDatabase = self.databases[self.activeDatabaseIndex]
if len(self.activeDatabase.spectra) > 0:
self.activeSpectrum = self.activeDatabase.spectra[0]
self.activeSpectrumName = self.activeDatabase.spectraNames[0]
self.updateDBInspector()
if self.parent is not None and refreshParent:
self.parent.populateRefSelector()
# if not self.noDBFound:
if len(self.databases) > 0:
self.activeDatabaseIndex = self.db_selector.currentIndex()
self.activeDatabase = self.databases[self.activeDatabaseIndex]
if len(self.activeDatabase.spectra) > 0:
self.activeSpectrum = self.activeDatabase.spectra[0]
self.activeSpectrumName = self.activeDatabase.spectraNames[0]
self.updateDBInspector()
if self.parent is not None and refreshParent:
self.parent.populateRefSelector()
def closeEvent(self, event):
# response = QtWidgets.QMessageBox.question(self, 'Warning', 'Exit without saving?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
......@@ -547,7 +549,6 @@ def main():
#start Application
app = QtWidgets.QApplication(sys.argv)
dbWin = DataBaseWindow(None)
# dbWin.showMaximized()
app.exec_()
......
......@@ -39,8 +39,8 @@ class ParticleEditor(object):
def createSafetyBackup(self):
self.actionCounter += 1
if self.actionCounter == self.backupFreq-1 or self.neverBackedUp:
print('backing up')
self.parent.parent.dataset.saveBackup()
backupname = self.parent.parent.dataset.saveBackup()
print('backing up as', backupname)
self.neverBackedUp = False
self.actionCounter = 0
......@@ -54,7 +54,7 @@ class ParticleEditor(object):
new_assignment = self.getNewEntry()
contourIndices = sorted(contourIndices) #we want to keep the contour with lowest index
print('selected contours:', contourIndices)
print('merging contours:', contourIndices)
self.createSafetyBackup()
#get contours:
contours = [self.parent.parent.dataset.particlecontours[i] for i in contourIndices]
......@@ -68,13 +68,16 @@ class ParticleEditor(object):
rangex = int(np.round((xmax-xmin)+2*padding))
rangey = int(np.round((ymax-ymin)+2*padding))
for i in range(len(cnt)):
cnt[i][0][0] -= xmin-padding
cnt[i][0][1] -= ymin-padding
img = np.zeros((rangey, rangex))
cv2.drawContours(img, [cnt], 0, 1, -1)
cv2.drawContours(img, [cnt], 0, 1, 1)
for i in contourIndices:
curCnt = self.parent.parent.dataset.particlecontours[i]
for i in range(len(curCnt)):
curCnt[i][0][0] -= xmin-padding
curCnt[i][0][1] -= ymin-padding
cv2.drawContours(img, [curCnt], -1, 1, -1)
cv2.drawContours(img, [curCnt], -1, 1, 1)
img = np.uint8(cv2.morphologyEx(img, cv2.MORPH_CLOSE, np.ones((3, 3))))
temp, contours, hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
......@@ -138,6 +141,7 @@ class ParticleEditor(object):
new_assignment = self.getNewEntry()
self.createSafetyBackup()
print(f'reassigning indices {contourindices} into {new_assignment}')
for partIndex in contourindices:
for specIndex in self.parent.particles2spectra[partIndex]:
self.parent.currentPolymers[specIndex] = new_assignment
......@@ -174,7 +178,7 @@ class ParticleEditor(object):
long, short = short, long
return long, short, longellipse, shortellipse, cv2.contourArea(cnt)
#if __name__ == '__main__':
# import
\ No newline at end of file
\ No newline at end of file
......@@ -295,7 +295,7 @@ class DataSet(object):
return os.path.join(self.path, "tmp.bmp")
def saveParticleData(self):
print('not saving ParticleData into text file..\nThe current output format might be wrong, if multiple spectra per particle are present...')
print('Not saving ParticleData into text file...:\nThe current output format might be wrong, if multiple spectra per particle are present...')
# if len(self.ramanscansortindex)>0:
# data = []
# pixelscale = (self.pixelscale_df if self.imagescanMode == 'df' else self.pixelscale_bf)
......@@ -315,9 +315,10 @@ class DataSet(object):
saveData(self, self.fname)
def saveBackup(self):
backupNameNotFound = True
# backupNameNotFound = True
inc = 0
while backupNameNotFound:
# while backupNameNotFound:
while True:
directory = os.path.dirname(self.fname)
filename = self.name + '_backup_' + str(inc) + '.pkl'
path = os.path.join(directory, filename)
......@@ -325,8 +326,9 @@ class DataSet(object):
inc += 1
else:
saveData(self, path)
backupNameNotFound = False
return filename
# backupNameNotFound = False
if __name__ == '__main__':
dset = loadData(r'D:\Projekte\Mikroplastik\Microcatch_BALT\Sampling Kampagne 1\MCI_2\MCI_2_all_kleiner500\MCI_2_ds1+2_all_kleiner500_10_1\MCI_2_ds1+2_all_kleiner500_10_1.pkl')
......@@ -176,14 +176,6 @@ class MeasureParticleWindow(QtWidgets.QMainWindow):
self.snapshotAct.triggered.connect(self.view.takeScreenshot)
self.snapshotAct.setDisabled(True)
self.checkCoordsAct = QtWidgets.QAction("Check Coordinate System", self)
self.checkCoordsAct.triggered.connect(self.view.checkCoords)
self.checkCoordsAct.setDisabled(True)
self.configCoordsAct = QtWidgets.QAction("Reconfigure Coordinate System", self)
self.configCoordsAct.triggered.connect(self.view.configureCoords)
self.configCoordsAct.setDisabled(True)
self.configRamanCtrlAct = QtWidgets.QAction("Configure Raman Control", self)
self.configRamanCtrlAct.triggered.connect(self.view.configureRamanControl)
if self.view.simulatedRaman:
......@@ -262,12 +254,9 @@ class MeasureParticleWindow(QtWidgets.QMainWindow):
self.modeMenu.addAction(self.detectParticleAct)
self.modeMenu.addAction(self.particelAnalysisAct)
self.toolsMenu = QtWidgets.QMenu("Tools")
self.toolsMenu = QtWidgets.QMenu("&Tools")
self.toolsMenu.addAction(self.snapshotAct)
self.toolsMenu.addAction(self.configRamanCtrlAct)
self.toolsMenu.addSeparator()
self.toolsMenu.addAction(self.checkCoordsAct)
self.toolsMenu.addAction(self.configCoordsAct)
self.helpMenu = QtWidgets.QMenu("&Help", self)
self.helpMenu.addAction(self.aboutAct)
......@@ -306,12 +295,12 @@ if __name__ == '__main__':
if not os.path.exists(logpath):
os.mkdir(logpath)
logname = os.path.join(logpath, 'logfile.txt')
# logname = os.path.join(os.path.split(__file__)[0], os.path.join("logfile.txt"))
fp = open(logname, "a")
sys.stderr = fp
sys.stdout = fp
print("starting GEPARD at: " + strftime("%d %b %Y %H:%M:%S", localtime()))
print("starting GEPARD at: " + strftime("%d %b %Y %H:%M:%S", localtime()), flush=True)
sys.stdout.flush()
app = QtWidgets.QApplication(sys.argv)
meas = MeasureParticleWindow()
......
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 14:33:22 2019
@author: brandt
"""
from PyQt5 import QtWidgets, QtCore
import numpy as np
import sys
class GetOffset(QtWidgets.QWidget):
def __init__(self, parent, ramanctrl):
super(GetOffset, self).__init__()
self.setWindowTitle('Get Coordinate Offset')
self.ramanctrl = ramanctrl
self.parent = parent
layout = QtWidgets.QVBoxLayout()
self.setLayout(layout)
layout.addWidget(QtWidgets.QLabel('Position of points'))
numPoints = 5
self.pointBtns = []
self.coordLabels = []
self.old_coords = []
self.new_coords = []
coordGroup = QtWidgets.QGroupBox()
coordLayout = QtWidgets.QGridLayout()
for i in range(numPoints):
self.coordLabels.append(QtWidgets.QLabel())
self.coordLabels[-1].setFixedWidth(200)
coordLayout.addWidget(i, 0, QtCore.Qt.AlignLeft)
self.pointBtns.append(QtWidgets.QPushButton('Point'+str(i+1)))
coordLayout.addWidget(i, )
def connectButtonAndLabel(self, btn, lbl, index):
btn.released.connect(lambda: self.readPoint(lbl, index))
def readPoint(self, lbl):
x, y, z = self.ramanctrl.getPosition()
z = self.ramanctrl.getUserZ()
lbl.setText(f'x = {np.round(x)} µm, y = {np.round(y)} µm, z = {np.round(z)} µm')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
offset = GetOffset(None)
offset.show()
sys.exit(app.exec_())
\ No newline at end of file
......@@ -63,7 +63,7 @@ def scan(ramanSettings, positions, controlclass, dataqueue, stopevent):
print("time:", time())
print("position:", x, y, z)
sys.stdout.flush() #remove this line after testing
ramanctrl.moveToAbsolutePosition(x, y, z)
ramanctrl.moveToAbsolutePosition(x, y, z, measurementRunning=True)
print("move done")
sys.stdout.flush()
ramanctrl.triggerMeasurement(i)
......@@ -178,6 +178,7 @@ class RamanScanUI(QtWidgets.QWidget):
self.dataqueue.join_thread()
self.view.unblockUI()
else:
QtWidgets.QMessageBox.about(self, 'Stopping', 'Stopping without acive process...')
return
self.close()
......@@ -273,7 +274,7 @@ class RamanScanUI(QtWidgets.QWidget):
self.dataset.ramanscandone = True
self.view.saveDataSet()
self.view.unblockUI()
self.view.switchMode("ParticleAnalysis")
# self.view.switchMode("ParticleAnalysis") #directly going to analysis is not feasible... We first have to export spectra etc...
self.progressbar.setValue(0)
self.progressbar.setEnabled(False)
self.progresstime.setEnabled(False)
......
......@@ -156,7 +156,7 @@ class SampleView(QtWidgets.QGraphicsView):
@QtCore.pyqtSlot()
def fitToWindow(self):
print("fitting to Window")
# print("fitting to Window")
brect = self.item.sceneBoundingRect()
self.fitInView(0, 0, brect.width(), brect.height(), QtCore.Qt.KeepAspectRatio)
self.scaleFactor = self.transform().m11()
......@@ -193,9 +193,11 @@ class SampleView(QtWidgets.QGraphicsView):
if self.ramanwidget.isVisible():
self.ramanwidget.setVisible(False)
if self.analysiswidget is None:
print('creating new analysiswidget')
self.analysiswidget = ParticleAnalysis(self)
self.analysiswidget.showMaximized()
else:
print('show maximized already exisiting analysiswidget')
self.analysiswidget.showMaximized()
# self.ramanwidget.setVisible(False)
......@@ -211,14 +213,21 @@ class SampleView(QtWidgets.QGraphicsView):
def open(self, fname):
self.saveDataSet()
if self.dataset is not None:
self.dataset.save()
#close all widgets
for widget in [self.detectionwidget, self.ramanwidget, self.oscanwidget, self.analysiswidget]:
if widget is not None:
widget.close()
widget.destroy()
self.contouritem.resetContours()
#close all widgets
for widget in [self.detectionwidget, self.ramanwidget, self.oscanwidget, self.analysiswidget]:
if widget is not None:
widget.close()
widget.destroy()
del widget
self.contouritem.resetContours()
# if self.dataset is not None:
# del self.dataset
# self.scene().removeItem(self.contouritem)
# del self.contouritem
# self.contouritem = SegmentationContours(self)
# self.scene().addItem(self.contouritem)
self.dataset = loadData(fname)
self.setMicroscopeMode()
......@@ -556,19 +565,5 @@ class SampleView(QtWidgets.QGraphicsView):
for item in self.ramanscanitems:
self.scene().removeItem(item)
self.ramanscanitems = []
def checkCoords(self):
if not os.path.exists(self.dataset.getImageName):
QtWidgets.QMessageBox.about(self, 'No Fullimage found', 'Optical scan was not complete.\nPlease acquire fullimage first with newly defined border points.')
else:
self.coordTestMode = True
QtWidgets.QMessageBox.about(self, 'Check Coordinate System', 'Microscope is moving to 5 positions.\nFirst, only x and y are moved, z only if x,y positions are confirmed')
points = (self.dataset.fitpoints if len(self.dataset.ramanpoints) == 0 else self.dataset.ramanpoints)
for i in range(5):
#get random scanindex:
point = points[np.random.randint(len(points))]
def configureCoords(self):
pass
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment