ramanscanui.py 11.6 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
from multiprocessing import Process, Queue, Event
import queue
26
from time import time
27
import sys
Hackmet's avatar
Hackmet committed
28
import os
29 30
from .external import tsp
from .uielements import TimeEstimateProgressbar
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

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

50 51 52 53 54 55 56 57 58 59 60
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
61
        
62 63 64 65 66 67 68 69
    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)
70
        ramanctrl.moveToAbsolutePosition(x, y, z)
71 72 73 74 75 76 77 78 79
        print("move done", flush=True)
        ramanctrl.triggerMeasurement(i)
        print("trigger done", flush=True)
        
        if stopevent.is_set():
            ramanctrl.disconnect()
            return
        
        dataqueue.put(i)
80

81 82 83
    ramanctrl.disconnect()
    if fp is not None:
        fp.close()
84

85
class RamanScanUI(QtWidgets.QWidget):
86
    imageUpdate = QtCore.pyqtSignal(str, name='imageUpdate')    #str = 'df' (= darkfield) or 'bf' (=bright field)
87 88
    ramanscanUpdate = QtCore.pyqtSignal()
    
89
    def __init__(self, ramanctrl, dataset, logpath='', parent=None):
90 91
        super().__init__(parent, QtCore.Qt.Window)
        self.view = parent
92
        self.logpath = logpath
93 94 95 96 97 98 99
        self.ramanctrl = ramanctrl
        self.dataset = dataset
        self.process = None
        
        vbox = QtWidgets.QVBoxLayout()
        hbox = QtWidgets.QHBoxLayout()
        
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        self.params = []
        for param in self.ramanctrl.ramanParameters:
            if param.dtype == 'int':
                self.params.append(QtWidgets.QSpinBox())
                self.params[-1].setMinimum(param.minVal)
                self.params[-1].setMaximum(param.maxVal)
                self.params[-1].setValue(param.value)
            if param.dtype == 'double':
                self.params.append(QtWidgets.QDoubleSpinBox())
                self.params[-1].setMinimum(param.minVal)
                self.params[-1].setMaximum(param.maxVal)
                self.params[-1].setValue(param.value)
            if param.dtype  == 'combobox':
                self.params.append(QtWidgets.QComboBox())
                self.params[-1].addItems([str(i) for i in param.valList])

116
        
117 118
        self.group2 = QtWidgets.QGroupBox("Raman settings", self)
        grid2 = QtWidgets.QFormLayout()
119
        
120 121 122 123
        for index, param in enumerate(self.params):
            param.setMinimumWidth(70)
            grid2.addRow(QtWidgets.QLabel(self.ramanctrl.ramanParameters[index].name), param)

124 125
        self.prun = QtWidgets.QPushButton("Raman scan", self)
        self.prun.released.connect(self.run)
126 127
        grid2.addRow(self.prun)
        self.group2.setLayout(grid2)
128 129 130 131
        
        self.pexit = QtWidgets.QPushButton("Cancel", self)
        self.pexit.released.connect(self.stopScan)
        self.prun.setEnabled(False)
132 133 134

        self.progressbar = TimeEstimateProgressbar()
        self.progressbar.disable()
135 136 137 138
        
        hbox.addStretch()
        hbox.addWidget(self.pexit)
        
139
        vbox.addWidget(self.group2)
140 141 142 143
        vbox.addLayout(hbox)
        vbox.addWidget(self.progressbar)
        
        self.setLayout(vbox)
144
        self.setWindowTitle("Raman Scan")
145
        self.setVisible(False)
146 147 148 149 150 151 152 153 154
    
    def makeGetFnameLambda(self, msg, path, fileType, btn):
        return lambda : self.getFName(msg, path, fileType, btn)
    
    def getFName(self, msg, path, filetype, btn):
        fname = QtWidgets.QFileDialog.getOpenFileName(self, msg, path, filetype)[0]
        btn.setText(fname.split('\\')[-1])
        btn.setMinimumSize(btn.sizeHint())
    
155 156
    def resetDataset(self, ds):
        self.dataset = ds
JosefBrandt's avatar
JosefBrandt committed
157
        numParticles = self.dataset.particleContainer.getNumberOfParticles()
158
        numMeasurements = self.dataset.particleContainer.getNumberOfMeasurements()
JosefBrandt's avatar
JosefBrandt committed
159
        if numParticles>0:
160
            self.prun.setEnabled(True)
161
            self.setWindowTitle(f'{numParticles} Particles ({numMeasurements}  Measurements)')
162 163 164 165 166 167 168 169 170
        
    @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:
Hackmet's avatar
Hackmet committed
171
                self.ramanctrl.finishMeasurement()
172
                self.timer.stop()
173
                self.progressbar.resetTimerAndCounter()
174
                self.processstopevent.set()
175
                self.process.join()
176 177
                self.dataqueue.close()
                self.dataqueue.join_thread()
178 179
                self.view.unblockUI()
            else:
Hackmet's avatar
Hackmet committed
180
                QtWidgets.QMessageBox.about(self, 'Stopping', 'Stopping without acive process...')
181 182 183 184 185 186 187 188 189 190 191 192 193 194
                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
195
        self.view.imparent.ramanSwitch.hide()
Hackmet's avatar
Hackmet committed
196 197
        self.view.setMicroscopeMode()
        
JosefBrandt's avatar
JosefBrandt committed
198
        points = np.asarray(self.dataset.particleContainer.getMeasurementPixelCoords())
199 200 201 202 203 204 205
        ramanSettings = {'filename': self.dataset.name,
                         'numPoints': len(points),
                         'path': self.dataset.path}
        for index, param in enumerate(self.params):
            try: ramanSettings[self.ramanctrl.ramanParameters[index].name] = self.ramanctrl.ramanParameters[index].value_of(param)
            except: print(param)
            
206 207 208 209 210 211 212 213 214 215
        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))
216
        scanpoints = np.array([self.dataset.mapToLengthRaman(p, microscopeMode=self.view.microscopeMode) for p in points[cmin,:]])
217 218 219 220 221 222 223 224 225 226 227 228
        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"
229
            for ramanScanIndex, measIndex in enumerate(cmin):
JosefBrandt's avatar
JosefBrandt committed
230
                self.dataset.particleContainer.setMeasurementScanIndex(measIndex, ramanScanIndex)
JosefBrandt's avatar
JosefBrandt committed
231
            
232 233
            self.view.saveDataSet()
            self.view.prepareAnalysis()
234
            self.view.zoomDisplay(2.0)
235 236 237 238 239 240 241 242 243 244 245 246 247 248
            if self.ramanctrl.name == 'RenishawCOM':
                QtWidgets.QMessageBox.about(self, "Info", "Control is headed over to Renishaw Instrument, Gepard is stopping here")
                ramanSettings['Points'] = scanpoints
                self.ramanctrl.initiateMeasurement(ramanSettings)
                self.ramanctrl.disconnect()
                self.dataset.ramanscandone = True
                self.view.saveDataSet()
                self.close()
                return
                
            else:
                self.view.highLightRamanIndex(0)
                self.view.blockUI()
                self.group2.setEnabled(False)
249 250 251
                self.progressbar.enable()
                self.progressbar.resetTimerAndCounter()
                self.progressbar.setMaxValue(len(scanpoints))
252 253 254 255 256 257 258 259 260 261 262 263 264 265
                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.logpath))
                self.process.start()
                self.starttime = time()
                self.timer = QtCore.QTimer(self)
                self.timer.timeout.connect(self.checkOnScan)
                self.timer.setSingleShot(True)
                self.timer.start(10000.)
266 267 268
    
    @QtCore.pyqtSlot()      
    def checkOnScan(self):
269 270 271 272
        try:
            i = self.dataqueue.get_nowait()
        except queue.Empty:
            i = -1
273 274
            
        if i>=0:
275
            self.progressbar.setValue(i+1)
Josef Brandt's avatar
 
Josef Brandt committed
276
            self.view.highLightRamanIndex(i+1)   #go to next scanmarker
277 278

            Npoints = len(self.dataset.particleContainer.getMeasurementPixelCoords())
279 280
            if i==Npoints-1:
                self.process.join()
281 282
                self.dataqueue.close()
                self.dataqueue.join_thread()
283 284 285
                self.dataset.ramanscandone = True
                self.view.saveDataSet()
                self.view.unblockUI()
286 287
                self.progressbar.resetTimerAndCounter()
                self.progressbar.disable()
288 289
                self.close()
                return
290
        self.timer.start(100.)
291