simulatedStage.py 12 KB
Newer Older
Josef Brandt's avatar
Josef Brandt committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# -*- 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/>.

Simulates a Microscope Stage with Camera.
"""
import os
from PyQt5 import QtWidgets, QtGui, QtCore
import cv2
import json
import numpy as np
from typing import List
29 30
from .imageGenerator import FakeCamera
from ...helperfunctions import getAppFolder
Josef Brandt's avatar
Josef Brandt committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66


class SimulatedStage(object):
    def __init__(self, ui: bool = True):
        super(SimulatedStage, self).__init__()
        self.currentpos: List[float] = [0.0, 0.0, 0.0]  # µm pos in x, y and z
        self.offset: List[float] = [0.0, 0.0, 0.0]  # µm offset in x, y and z
        self.rotMatrix: np.ndarray = np.zeros((3, 3))
        self.camera: FakeCamera = FakeCamera()
        self.camera.updateImageAtPosition(self.currentpos)
        self.filepath: str = self._getFilePath()
        self.uiEnabled = ui
        if self.uiEnabled:
            self.ui: SimulatedStageUI = SimulatedStageUI(self)
            self.ui.show()

    def getCurrentCameraImage(self) -> np.ndarray:
        return self.camera.currentImage

    def moveToPosition(self, x: float, y: float, z: float):
        self.currentpos = [x, y, z]
        self.saveConfigToFile()
        self.camera.updateImageAtPosition(self.currentpos)
        if self.uiEnabled:
            self.ui.updateCameraImage()
            self.ui.updateStageCoords()

    def connect(self) -> None:
        self.updateConfigFromFile()
        if self.uiEnabled:
            self.ui.setEnabled(True)

    def disconnect(self) -> None:
        self.saveConfigToFile()
        if self.uiEnabled:
            self.ui.setEnabled(False)
67
        self.camera.close()
Josef Brandt's avatar
Josef Brandt committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

    def updateConfigFromFile(self) -> None:
        if os.path.exists(self.filepath):
            with open(self.filepath, 'r') as fp:
                try:
                    configHasChanged: bool = self._dictToConfig(json.load(fp))
                except json.JSONDecodeError:
                    # TODO: get reference to logger and log info that loading config failed..
                    print('failed updating simulated stage state from file..')
                    return

                if configHasChanged:
                    self.camera.updateImageAtPosition(self.currentpos)
                    if self.uiEnabled:
                        self.ui.updateCameraImage()
                        self.ui.updateStageCoords()

    def saveConfigToFile(self) -> None:
        if self.filepath != '':
            with open(self.filepath, 'w') as fp:
                json.dump(self._configToDict(), fp)

    def _getFilePath(self) -> str:
91
        path: str = getAppFolder()
Josef Brandt's avatar
Josef Brandt committed
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        return os.path.join(path, 'simulatedStageConfig.txt')

    def _configToDict(self) -> dict:
        return {'currentPos': self.currentpos}

    def _dictToConfig(self, inputDict: dict) -> bool:
        configChanged: bool = False
        if self.currentpos != inputDict['currentPos']:
            self.currentpos = inputDict['currentPos']
            configChanged = True
        return configChanged


class SimulatedStageUI(QtWidgets.QWidget):
    def __init__(self, stageParent: SimulatedStage):
        super(SimulatedStageUI, self).__init__()
        self.stageParent: SimulatedStage = stageParent
        self.updateTimer: QtCore.QTimer = QtCore.QTimer()
        self.updateTimer.setSingleShot(False)
        self.updateTimer.timeout.connect(self.stageParent.updateConfigFromFile)
112
        self.updateTimer.start(200)
Josef Brandt's avatar
Josef Brandt committed
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 151 152 153 154 155 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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

        self.setWindowTitle('Simulated Microscope Stage')
        coordsGroup: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Stage Coordinates')
        coordsLayout: QtWidgets.QHBoxLayout = QtWidgets.QHBoxLayout()
        coordsGroup.setLayout(coordsLayout)
        self.labelX: QtWidgets.QLabel = QtWidgets.QLabel()
        self.labelY: QtWidgets.QLabel = QtWidgets.QLabel()
        self.labelZ: QtWidgets.QLabel = QtWidgets.QLabel()
        for label in [self.labelX, self.labelY, self.labelZ]:
            coordsLayout.addWidget(label)

        self.camView: QtWidgets.QGraphicsView = self._createCamView()

        self.stepSizeSpinbox: QtWidgets.QSpinBox = QtWidgets.QSpinBox()
        self.stageControls: QtWidgets.QGroupBox = self._createControls()

        layout: QtWidgets.QHBoxLayout = QtWidgets.QHBoxLayout()
        self.setLayout(layout)

        leftColumn: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout()
        leftColumn.addWidget(coordsGroup)
        leftColumn.addWidget(QtWidgets.QLabel('Camera Image'))
        leftColumn.addWidget(self.camView)
        leftColumn.addWidget(self.stageControls)

        layout.addLayout(leftColumn)

        rightColumn: QtWidgets.QGroupBox = self._getExtrasColumn()
        layout.addWidget(rightColumn)
        self.updateCameraImage()
        self.updateStageCoords()

    def _createCamView(self) -> QtWidgets.QGraphicsView:
        camView: QtWidgets.QGraphicsView = QtWidgets.QGraphicsView()
        camView.item = QtWidgets.QGraphicsPixmapItem()
        scene = QtWidgets.QGraphicsScene(camView)
        scene.addItem(camView.item)
        camView.setScene(scene)
        camView.scale(1.0, 1.0)
        return camView

    def _createControls(self) -> QtWidgets.QGroupBox:
        def makeBtnLambda(_btn: QtWidgets.QPushButton):
            return lambda: self._moveBtnPressed(_btn)

        controls: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Stage Controls')
        layout: QtWidgets.QGridLayout = QtWidgets.QGridLayout()
        controls.setLayout(layout)

        stepSizeLayout: QtWidgets.QHBoxLayout = QtWidgets.QHBoxLayout()
        stepSizeLayout.addStretch()
        stepSizeLayout.addWidget(QtWidgets.QLabel('Set Step Size (µm): '))
        stepSizeLayout.addWidget(self.stepSizeSpinbox)
        stepSizeLayout.addStretch()

        self.stepSizeSpinbox.setMinimum(0)
        self.stepSizeSpinbox.setValue(10)
        self.stepSizeSpinbox.setMaximum(100000)
        self.stepSizeSpinbox.setSingleStep(50)
        self.stepSizeSpinbox.setMaximumWidth(75)

        xyGroup: QtWidgets.QGroupBox = QtWidgets.QGroupBox('XY Controls')
        xyLayout: QtWidgets.QGridLayout = QtWidgets.QGridLayout()
        xyGroup.setLayout(xyLayout)
        upBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('UP')
        downBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('DOWN')
        leftBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('LEFT')
        rightBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('RIGHT')
        for btn in [upBtn, downBtn, leftBtn, rightBtn]:
            btn.clicked.connect(makeBtnLambda(btn))

        xyLayout.addWidget(upBtn, 0, 1)
        xyLayout.addWidget(leftBtn, 1, 0)
        xyLayout.addWidget(rightBtn, 1, 2)
        xyLayout.addWidget(downBtn, 2, 1)

        zGroup: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Z Controls')
        zLayout: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout()
        zGroup.setLayout(zLayout)

        zUpBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('HIGHER')
        zDownBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('LOWER')
        for btn in [zUpBtn, zDownBtn]:
            btn.clicked.connect(makeBtnLambda(btn))
            zLayout.addWidget(btn)

        layout.addLayout(stepSizeLayout, 0, 0, 1, 2)
        layout.addWidget(xyGroup, 1, 0)
        layout.addWidget(zGroup, 1, 1)
        return controls

    def _getExtrasColumn(self) -> QtWidgets.QGroupBox:
        def makePresetBtnLambda(pressedBtn: QtWidgets.QPushButton):
            return lambda: self._moveToPresetPosition(pressedBtn)

        extrasGroup: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Extra Operations')
        extrasLayout: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout()
        extrasGroup.setLayout(extrasLayout)

        presetPositionsGroup: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Move to preset positions')
        presetPositionsLayout: QtWidgets.QGridLayout = QtWidgets.QGridLayout()
        presetPositionsGroup.setLayout(presetPositionsLayout)

        upperLeftBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('UpperLeft')
        lowerLeftBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('LowerLeft')
        upperRightBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('UpperRight')
        lowerRightBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('LowerRight')
        centerBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('Center')
        for btn in [upperLeftBtn, upperRightBtn, lowerLeftBtn, lowerRightBtn, centerBtn]:
            btn.clicked.connect(makePresetBtnLambda(btn))

        presetPositionsLayout.addWidget(upperLeftBtn, 0, 0)
        presetPositionsLayout.addWidget(upperRightBtn, 0, 2)
        presetPositionsLayout.addWidget(centerBtn, 1, 1)
        presetPositionsLayout.addWidget(lowerLeftBtn, 2, 0)
        presetPositionsLayout.addWidget(lowerRightBtn, 2, 2)

        coordGroup: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Modify Coordinate System')
        coordLayout: QtWidgets.QFormLayout = QtWidgets.QFormLayout()
        coordGroup.setLayout(coordLayout)

        extrasLayout.addWidget(presetPositionsGroup)
        extrasLayout.addWidget(coordGroup)
        return extrasGroup

    def _moveBtnPressed(self, btn: QtWidgets.QPushButton) -> None:
        label: str = btn.text()
        newPos: List[float] = self.stageParent.currentpos
        if label == 'UP':
            newPos[1] += self.stepSizeSpinbox.value()
        elif label == 'DOWN':
            newPos[1] -= self.stepSizeSpinbox.value()
        elif label == 'LEFT':
            newPos[0] -= self.stepSizeSpinbox.value()
        elif label == 'RIGHT':
            newPos[0] += self.stepSizeSpinbox.value()
        elif label == 'HIGHER':
            newPos[2] += self.stepSizeSpinbox.value()
        elif label == 'LOWER':
            newPos[2] -= self.stepSizeSpinbox.value()
        
        self.stageParent.moveToPosition(newPos[0], newPos[1], newPos[2])

    def _moveToPresetPosition(self, btn: QtWidgets.QPushButton, stepSize: float = 1000) -> None:
        label: str = btn.text()
        newPos: List[float] = [0.0, 0.0, 0.0]
        if label == 'UpperLeft':
            newPos[0] -= stepSize
            newPos[1] += stepSize
        elif label == 'UpperRight':
            newPos[0] += stepSize
            newPos[1] += stepSize
        elif label == 'LowerLeft':
            newPos[0] -= stepSize
            newPos[1] -= stepSize
        elif label == 'LowerRight':
            newPos[0] += stepSize
            newPos[1] -= stepSize
        elif label == 'Center':
            pass

        self.stageParent.moveToPosition(newPos[0], newPos[1], newPos[2])

    def updateCameraImage(self) -> None:
        img: np.ndarray = self.stageParent.camera.currentImage.copy()
        height, width, channel = img.shape
        centerX, centerY = int(round(width/2)), int(round(height/2))
        cv2.circle(img, (centerX, centerY), 20, (0, 255, 0), thickness=2)
        bytesPerLine = 3 * width
        pixmap = QtGui.QPixmap()
        pixmap.convertFromImage(QtGui.QImage(img.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888))
        self.camView.item.setPixmap(pixmap)

    def updateStageCoords(self) -> None:
        self.labelX.setText(f'x: {round(self.stageParent.currentpos[0], 2)} µm')
        self.labelY.setText(f'y: {round(self.stageParent.currentpos[1], 2)} µm')
        self.labelZ.setText(f'z: {round(self.stageParent.currentpos[2], 2)} µm')


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    stage: SimulatedStage = SimulatedStage(ui=True)
    app.exec_()