Commit eb5a3c56 authored by Lars Bittrich's avatar Lars Bittrich

new logpath handling; Qt AppLocalDataLocation is now used to obtain an OS...

new logpath handling; Qt AppLocalDataLocation is now used to obtain an OS independent standard path for such information; since this path is needed multiple times it is shared as parameter to all relevant modules and processes
parent 38d7b35f
......@@ -25,17 +25,16 @@ from ramancom.ramancontrol import defaultPath
from ramancom.ramanSwitch import RamanSwitch
from colorlegend import ColorLegend
import os
from pathlib import Path
class MeasureParticleWindow(QtWidgets.QMainWindow):
def __init__(self):
def __init__(self, logpath):
super(MeasureParticleWindow, self).__init__()
self.setWindowTitle("GEPARD")
self.resize(900, 700)
self.view = SampleView()
self.view = SampleView(logpath)
self.view.imparent = self
self.view.ScalingChanged.connect(self.scalingChanged)
self.scalebar = ScaleBar(self)
......@@ -288,21 +287,26 @@ class MeasureParticleWindow(QtWidgets.QMainWindow):
self.addToolBar(QtCore.Qt.LeftToolBarArea, self.toolbar)
if __name__ == '__main__':
import sys
from time import localtime, strftime
logpath = os.path.join(Path.home(),'gepard')
if not os.path.exists(logpath):
os.mkdir(logpath)
logname = os.path.join(logpath, 'logfile.txt')
fp = open(logname, "a")
sys.stderr = fp
sys.stdout = fp
print("starting GEPARD at: " + strftime("%d %b %Y %H:%M:%S", localtime()), flush=True)
sys.stdout.flush()
app = QtWidgets.QApplication(sys.argv)
meas = MeasureParticleWindow()
app.setApplicationName("GEPARD") # appname needed for logpath
logpath = QtCore.QStandardPaths.writableLocation(
QtCore.QStandardPaths.AppLocalDataLocation)
if logpath != "":
if not os.path.exists(logpath):
os.mkdir(logpath)
logname = os.path.join(logpath, 'logfile.txt')
fp = open(logname, "a")
sys.stderr = fp
sys.stdout = fp
print("starting GEPARD at: " + strftime("%d %b %Y %H:%M:%S", localtime()),
flush=True)
meas = MeasureParticleWindow(logpath)
meas.showMaximized()
ret = app.exec_()
\ No newline at end of file
......@@ -27,54 +27,59 @@ from imagestitch import imageStacking
import os
import cv2
from helperfunctions import cv2imread_fix, cv2imwrite_fix
from time import sleep, time
from time import time
import datetime
import sys
from pathlib import Path
#def scan(path, sol, zpositions, grid, controlclass, connection, ishdr=False):
def scan(path, sol, zpositions, grid, controlclass, dataqueue, stopevent, ishdr=False):
print('starting new optical scan')
sys.stdout.flush()
def scan(path, sol, zpositions, grid, controlclass, dataqueue,
stopevent, logpath='', ishdr=False):
if ishdr:
merge_mertens = cv2.createMergeMertens()
logpath = os.path.join(Path.home(),'gepard', 'scanlog.txt')
with open(logpath, "a") as fp:
sys.stderr = fp
sys.stdout = fp
merge_mertens = cv2.createMergeMertens()
fp = None
if logpath != '':
try:
fp = open(os.path.join(logpath, 'scanlog.txt'), 'a')
sys.stderr = fp
sys.stdout = fp
except IOError:
print('separate loging failed', flush=True)
pass
print('starting new optical scan', flush=True)
ramanctrl = controlclass()
ramanctrl.connect()
zlist = list(enumerate(zpositions))
for i, p in enumerate(grid):
x, y = p
z = sol[0]*x + sol[1]*y + sol[2]
for k, zk in (zlist if i%2==0 else zlist[::-1]):
name = f"image_{i}_{k}.bmp"
print("time:", time())
zik = z+zk
assert not np.isnan(zik)
print("moving to:", x, y, zik)
ramanctrl.moveToAbsolutePosition(x, y, zik)
if ishdr:
img_list = []
fname = os.path.join(path,f"tmp.bmp")
values = [5.,25.,100.]
for j, val in enumerate(values if (i%2+k%2)%2==0 else reversed(values)):
ramanctrl.setBrightness(val)
ramanctrl.saveImage(fname)
img_list.append(cv2imread_fix(fname))
res_mertens = merge_mertens.process(img_list)
res_mertens_8bit = np.clip(res_mertens*255, 0, 255).astype('uint8')
cv2imwrite_fix(os.path.join(path,name), res_mertens_8bit)
else:
ramanctrl.saveImage(os.path.join(path,name))
if stopevent.is_set():
ramanctrl.disconnect()
return
dataqueue.put(i)
ramanctrl.disconnect()
ramanctrl = controlclass()
ramanctrl.connect()
zlist = list(enumerate(zpositions))
for i, p in enumerate(grid):
x, y = p
z = sol[0]*x + sol[1]*y + sol[2]
for k, zk in (zlist if i%2==0 else zlist[::-1]):
name = f"image_{i}_{k}.bmp"
print("time:", time(), flush=True)
zik = z+zk
assert not np.isnan(zik)
print("moving to:", x, y, zik, flush=True)
ramanctrl.moveToAbsolutePosition(x, y, zik)
if ishdr:
img_list = []
fname = os.path.join(path,f"tmp.bmp")
values = [5.,25.,100.]
for j, val in enumerate(values if (i%2+k%2)%2==0 else reversed(values)):
ramanctrl.setBrightness(val)
ramanctrl.saveImage(fname)
img_list.append(cv2imread_fix(fname))
res_mertens = merge_mertens.process(img_list)
res_mertens_8bit = np.clip(res_mertens*255, 0, 255).astype('uint8')
cv2imwrite_fix(os.path.join(path,name), res_mertens_8bit)
else:
ramanctrl.saveImage(os.path.join(path,name))
if stopevent.is_set():
ramanctrl.disconnect()
return
dataqueue.put(i)
ramanctrl.disconnect()
if fp is not None:
fp.close()
def loadAndPasteImage(srcnames, fullimage, fullzval, width, height,
......@@ -212,8 +217,9 @@ class OpticalScan(QtWidgets.QWidget):
imageUpdate = QtCore.pyqtSignal(str, name='imageUpdate') #str = 'df' (= darkfield) or 'bf' (=bright field)
boundaryUpdate = QtCore.pyqtSignal()
def __init__(self, ramanctrl, dataset, parent=None):
def __init__(self, ramanctrl, dataset, logpath='', parent=None):
super().__init__(parent, QtCore.Qt.Window)
self.logpath = logpath
self.view = parent
vbox = QtWidgets.QVBoxLayout()
pointgroup = QtWidgets.QGroupBox("Point coordinates [µm]", self)
......@@ -508,7 +514,7 @@ class OpticalScan(QtWidgets.QWidget):
A = np.ones((points.shape[0],3))
A[:,:2] = points[:,:2]
b = points[:,2]
sol = np.linalg.lstsq(A,b)[0]
sol = np.linalg.lstsq(A, b, rcond=None)[0]
self.dataset.heightmap = sol
print("Fit deviation:", sol[0]*points[:,0]+sol[1]*points[:,1]+sol[2] -points[:,2] )
......@@ -545,7 +551,8 @@ class OpticalScan(QtWidgets.QWidget):
self.dataqueue = Queue()
self.process = Process(target=scan, args=(path, sol, self.dataset.zpositions,
self.dataset.grid, self.ramanctrl.__class__,
self.dataqueue, self.processstopevent, self.hdrcheck.isChecked()))
self.dataqueue, self.processstopevent,
self.logpath, self.hdrcheck.isChecked()))
self.process.start()
self.starttime = time()
self.progresstime.setEnabled(True)
......@@ -619,8 +626,10 @@ class OpticalScan(QtWidgets.QWidget):
if __name__ == "__main__":
from ramancom.simulatedraman import SimulatedRaman
from dataset import DataSet
app = QtWidgets.QApplication(sys.argv)
optscan = OpticalScan(SimulatedRaman())
ds = DataSet('Test')
optscan = OpticalScan(SimulatedRaman(), ds)
optscan.show()
sys.exit(app.exec_())
\ No newline at end of file
......@@ -23,12 +23,11 @@ from PyQt5 import QtCore, QtWidgets
import numpy as np
from multiprocessing import Process, Queue, Event
import queue
from time import sleep, time
from time import time
from external import tsp
import datetime
import sys
import os
from pathlib import Path
def reorder(points, N=20):
y0, y1 = points[:,1].min(), points[:,1].max()
......@@ -48,44 +47,49 @@ def reorder(points, N=20):
assert np.unique(newind).shape[0]==allind.shape[0]
return newind
def scan(ramanSettings, positions, controlclass, dataqueue, stopevent):
logpath = os.path.join(Path.home(),'gepard', 'ramanscanlog.txt')
with open(logpath, "a") as fp:
sys.stderr = fp
sys.stdout = fp
def scan(ramanSettings, positions, controlclass, dataqueue, stopevent,
logpath=''):
fp = None
if logpath != '':
try:
fp = open(os.path.join(logpath, 'ramanscanlog.txt'), 'a')
sys.stderr = fp
sys.stdout = fp
except IOError:
print('separate loging failed', flush=True)
pass
ramanctrl = controlclass()
ramanctrl.connect()
print("connected:", time())
ramanctrl.initiateMeasurement(ramanSettings)
for i, p in enumerate(positions):
x, y, z = p
print("time:", time())
print("position:", x, y, z)
sys.stdout.flush() #remove this line after testing
ramanctrl.moveToAbsolutePosition(x, y, z, measurementRunning=True)
print("move done")
sys.stdout.flush()
ramanctrl.triggerMeasurement(i)
print("trigger done")
sys.stdout.flush()
if stopevent.is_set():
ramanctrl.disconnect()
return
dataqueue.put(i)
ramanctrl.disconnect()
ramanctrl = controlclass()
ramanctrl.connect()
print("connected:", time(), flush=True)
ramanctrl.initiateMeasurement(ramanSettings)
for i, p in enumerate(positions):
x, y, z = p
print("time:", time(), flush=True)
print("position:", x, y, z, flush=True)
ramanctrl.moveToAbsolutePosition(x, y, z, measurementRunning=True)
print("move done", flush=True)
ramanctrl.triggerMeasurement(i)
print("trigger done", flush=True)
if stopevent.is_set():
ramanctrl.disconnect()
return
dataqueue.put(i)
ramanctrl.disconnect()
if fp is not None:
fp.close()
class RamanScanUI(QtWidgets.QWidget):
imageUpdate = QtCore.pyqtSignal(str, name='imageUpdate') #str = 'df' (= darkfield) or 'bf' (=bright field)
ramanscanUpdate = QtCore.pyqtSignal()
def __init__(self, ramanctrl, dataset, parent=None):
def __init__(self, ramanctrl, dataset, logpath='', parent=None):
super().__init__(parent, QtCore.Qt.Window)
self.view = parent
self.logpath = logpath
self.ramanctrl = ramanctrl
self.dataset = dataset
self.process = None
......@@ -242,7 +246,11 @@ class RamanScanUI(QtWidgets.QWidget):
self.ramanctrl.disconnect()
self.processstopevent = Event()
self.dataqueue = Queue()
self.process = Process(target=scan, args=(ramanSettings, scanpoints, self.ramanctrl.__class__, self.dataqueue, self.processstopevent))
self.process = Process(target=scan, args=(ramanSettings, scanpoints,
self.ramanctrl.__class__,
self.dataqueue,
self.processstopevent,
self.logpath))
self.process.start()
self.starttime = time()
self.timer = QtCore.QTimer(self)
......
......@@ -35,9 +35,10 @@ from ramancom.configRaman import RamanConfigWin
class SampleView(QtWidgets.QGraphicsView):
ScalingChanged = QtCore.pyqtSignal(float)
def __init__(self):
def __init__(self, logpath):
super(SampleView, self).__init__()
self.logpath = logpath
self.item = QtWidgets.QGraphicsPixmapItem()
self.item.setPos(0, 0)
self.item.setAcceptedMouseButtons(QtCore.Qt.NoButton)
......@@ -77,9 +78,9 @@ class SampleView(QtWidgets.QGraphicsView):
self.contouritem = SegmentationContours(self)
scene.addItem(self.contouritem)
self.detectionwidget = None
self.ramanwidget = RamanScanUI(self.ramanctrl, None, self)
self.ramanwidget = RamanScanUI(self.ramanctrl, None, self.logpath, self)
self.ramanwidget.imageUpdate.connect(self.loadPixmap)
self.oscanwidget = OpticalScan(self.ramanctrl, None, self)
self.oscanwidget = OpticalScan(self.ramanctrl, None, self.logpath, self)
self.oscanwidget.imageUpdate.connect(self.loadPixmap)
self.oscanwidget.boundaryUpdate.connect(self.resetBoundary)
self.analysiswidget = None
......@@ -194,7 +195,7 @@ class SampleView(QtWidgets.QGraphicsView):
self.ramanwidget.setVisible(False)
if self.analysiswidget is None:
print('creating new analysiswidget')
self.analysiswidget = ParticleAnalysis(self)
self.analysiswidget = ParticleAnalysis(self.dataset, self)
self.analysiswidget.showMaximized()
else:
print('show maximized already exisiting analysiswidget')
......@@ -477,7 +478,7 @@ class SampleView(QtWidgets.QGraphicsView):
self.boundaryitems = edges, nodes
self.resetScanPositions()
@QtCore.pyqtSlot(int, float)
@QtCore.pyqtSlot(int, bool)
def selectContour(self, index, centerOn=True):
if self.analysiswidget is not None:
if self.analysiswidget.uniquePolymers is not None:
......
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