ramanscanui.py 9.96 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# -*- 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 QtCore, QtWidgets
import numpy as np
24 25 26
from multiprocessing import Process, Queue, Event
import queue
from time import sleep, time, localtime, strftime
27
import datetime
28
from externalmodules import tsp
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
import sys

def reorder(points, N=20):
    y0, y1 = points[:,1].min(), points[:,1].max()
    y = np.linspace(y0,y1+.1,N+1)
    allind = np.arange(points.shape[0])
    newind = []
    for i, yi in enumerate(y[:-1]):
        yi1 = y[i+1]
        indy = allind[(points[:,1]>=yi)&(points[:,1]<yi1)]
        p = points[indy,:]
        indx = p[:,0].argsort()
        if i%2==1:
            newind.append(indy[indx])
        else:
            newind.append(indy[indx[::-1]])
    newind = np.concatenate(newind, axis=0)
    assert np.unique(newind).shape[0]==allind.shape[0]
    return newind

49 50
def scan(name, accu, inttime, positions, controlclass, dataqueue, stopevent):
    
51 52 53 54 55 56 57
    with open("ramanscanlog.txt", "a") as fp:
        sys.stderr = fp
        sys.stdout = fp
        
        ramanctrl = controlclass()
        ramanctrl.connect()
        ramanctrl.initiateTimeSeriesScan(name, len(positions), accu, inttime)
58
        print("starting Raman Scan at: " + strftime("%d %b %Y %H:%M:%S", localtime()))
59 60
        for i, p in enumerate(positions):
            x, y, z = p
61 62 63
            
            print('Measuring particle index {} at location {}, time = {}'.format(i, (x, y, z), strftime("%H:%M:%S", localtime())))
            sys.stdout.flush()          #remove after testing
64 65
            ramanctrl.moveToAbsolutePosition(x, y, z)
            ramanctrl.nextTimeSeriesScan(i)
66 67 68 69 70

            if stopevent.is_set():
                ramanctrl.disconnect()
                return
            dataqueue.put(i)
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        ramanctrl.disconnect()

class RamanScanUI(QtWidgets.QWidget):
    imageUpdate = QtCore.pyqtSignal(name='imageUpdate')
    ramanscanUpdate = QtCore.pyqtSignal()
    
    def __init__(self, ramanctrl, dataset, parent=None):
        super().__init__(parent, QtCore.Qt.Window)
        self.view = parent
        self.ramanctrl = ramanctrl
        self.dataset = dataset
        self.process = None
        
        vbox = QtWidgets.QVBoxLayout()
        hbox = QtWidgets.QHBoxLayout()
        
        labelaccu = QtWidgets.QLabel("Accumulations:", self)
        self.accumulationsedit = QtWidgets.QSpinBox(self)
        self.accumulationsedit.setMinimum(1)
        self.accumulationsedit.setMaximum(1000)
        self.accumulationsedit.setValue(10)
        self.accumulationsedit.setMinimumWidth(70)
        
        labelinttime = QtWidgets.QLabel("Integration time:", self)
        self.inttimeedit = QtWidgets.QDoubleSpinBox(self)
        self.inttimeedit.setMinimum(0.1)
        self.inttimeedit.setMaximum(100.0)
        self.inttimeedit.setDecimals(1)
        self.inttimeedit.setValue(0.1)
        self.inttimeedit.setSingleStep(0.1)
        self.inttimeedit.setMinimumWidth(70)
        
        group2 = QtWidgets.QGroupBox("Raman settings", self)
        grid2 = QtWidgets.QGridLayout()
        grid2.addWidget(labelaccu, 0, 0, QtCore.Qt.AlignLeft)
        grid2.addWidget(self.accumulationsedit, 0, 1, QtCore.Qt.AlignRight)
        grid2.addWidget(labelinttime, 1, 0, QtCore.Qt.AlignLeft)
        grid2.addWidget(self.inttimeedit, 1, 1, QtCore.Qt.AlignRight)
        self.prun = QtWidgets.QPushButton("Raman scan", self)
        self.prun.released.connect(self.run)
        grid2.addWidget(self.prun, 1, 2, QtCore.Qt.AlignRight)
        group2.setLayout(grid2)
        
        self.pexit = QtWidgets.QPushButton("Cancel", self)
        self.pexit.released.connect(self.stopScan)
        self.prun.setEnabled(False)
        self.progressbar = QtWidgets.QProgressBar(self)
        self.timelabeltext = "Estimated time to finish: "
        self.progresstime = QtWidgets.QLabel(self.timelabeltext, self)
        self.progresstime.setEnabled(False)
        self.progressbar.setEnabled(False)
        
        hbox.addStretch()
        hbox.addWidget(self.pexit)
        
        vbox.addWidget(group2)
        vbox.addLayout(hbox)
        vbox.addWidget(self.progresstime)
        vbox.addWidget(self.progressbar)
        
        self.setLayout(vbox)
        self.setWindowTitle("Particle Detection")
        #self.show()
        self.setVisible(False)
        
    def resetDataset(self, ds):
        self.dataset = ds
        if len(self.dataset.ramanpoints)>0:
            self.prun.setEnabled(True)
            self.setWindowTitle(str(len(ds.ramanpoints)) + " Particles")
        
    @QtCore.pyqtSlot()
    def stopScan(self):
        if self.process is not None and self.process.is_alive():
            reply = QtWidgets.QMessageBox.question(self, 'Stop raman scan?',
                                "Do you want to terminate the running scan?",
                                QtWidgets.QMessageBox.Yes | 
                                QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
            if reply == QtWidgets.QMessageBox.Yes:
                self.timer.stop()
151 152
#                self.connection.send("stop")
                self.processstopevent.set()
153
                self.process.join()
154 155
                self.dataqueue.close()
                self.dataqueue.join_thread()
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
                self.view.unblockUI()
            else:
                return
        self.close()
        
    @QtCore.pyqtSlot()
    def run(self):
        if self.dataset.readin:
            reply = QtWidgets.QMessageBox.critical(self, 'Dataset is newly read from disk!',
                "Coordinate systems might have changed since. Do you want to continue with saved coordinates?", 
                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)

            if reply == QtWidgets.QMessageBox.Yes:
                self.dataset.readin = False
            else:
                return
        accu = self.accumulationsedit.value()
        inttime = self.inttimeedit.value()
        points = np.asarray(self.dataset.ramanpoints)
        lmin = None
        for i in range(20,41):
            c = reorder(points, i)
            l = np.sum(np.sqrt(np.sum(np.diff(points[c,:],axis=0)**2,axis=1)))
            if lmin is None or l<lmin:
                lmin = l
                cmin = c
        if len(points)<20000:
            cmin, T = tsp.tspcomp(np.double(points), np.int32(cmin))
        assert np.all(np.sort(cmin)==np.arange(len(points), dtype=np.int32))
        scanpoints = np.array([self.dataset.mapToLengthRaman(p) for p in points[cmin,:]])
        zmin, zmax = scanpoints[:,2].min(), scanpoints[:,2].max()
        softwarez = self.ramanctrl.getSoftwareZ()  # get current software z
        zmin -= softwarez
        zmax -= softwarez
        reply = QtWidgets.QMessageBox.question(self, 'Starting raman scan',
            "Please switch to Raman laser. Microscope will move"\
            " (%4.0f,%4.0f) µm relative to current position. Proceed?"%(zmin,zmax), 
            QtWidgets.QMessageBox.Yes | 
            QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)

        if reply == QtWidgets.QMessageBox.Yes:
            self.dataset.mode = "ramanscan"
            self.dataset.ramanscansortindex = cmin
            self.dataset.saveParticleData()
            self.view.saveDataSet()
            self.view.prepareAnalysis()
            self.view.scaleImage(2.0)
            self.view.highLightRamanIndex(0)
            self.view.blockUI()
            self.prun.setEnabled(False)
            self.progresstime.setEnabled(True)
            self.progressbar.setEnabled(True)
            self.progressbar.setRange(0, len(scanpoints))
            self.progressbar.setValue(0)
            self.ramanctrl.disconnect()
211 212 213
            self.processstopevent = Event()
            self.dataqueue = Queue()
            self.process = Process(target=scan, args=(self.dataset.name, accu, inttime, scanpoints, self.ramanctrl.__class__, self.dataqueue, self.processstopevent))
214 215 216 217 218 219 220 221 222
            self.process.start()
            self.starttime = time()
            self.timer = QtCore.QTimer(self)
            self.timer.timeout.connect(self.checkOnScan)
            self.timer.setSingleShot(True)
            self.timer.start(100.)
    
    @QtCore.pyqtSlot()      
    def checkOnScan(self):
223 224 225 226 227
        try:
            i = self.dataqueue.get_nowait()
        except queue.Empty:
            i = -1
        if i >= 0:
228 229 230 231 232 233 234 235 236 237
            self.progressbar.setValue(i+1)
            self.view.highLightRamanIndex(i+1)
            Npoints = len(self.dataset.ramanpoints)
            if i>3:
                timerunning = time()-self.starttime
                ttot = timerunning*Npoints/(i+1)
                time2go = ttot - timerunning
                self.progresstime.setText(self.timelabeltext + str(datetime.timedelta(seconds=round(time2go))))
            if i==Npoints-1:
                self.process.join()
238 239
                self.dataqueue.close()
                self.dataqueue.join_thread()
240 241 242 243 244 245 246 247 248 249 250
                self.dataset.ramanscandone = True
                self.view.saveDataSet()
                self.view.unblockUI()
                self.view.switchMode("ParticleAnalysis")
                self.progressbar.setValue(0)
                self.progressbar.setEnabled(False)
                self.progresstime.setEnabled(False)
                self.close()
                return
        self.timer.start(100.)