coordTransferGUI.py 12.5 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 24 25 26 27 28 29 30 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 67 68 69 70 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 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
from PyQt5 import QtWidgets, QtGui, QtCore
import numpy as np
from typing import List
from copy import deepcopy
from ..coordinatetransform import ImageMarker, TrayMarker, getTransform
from ..ramancom.ramanbase import RamanBase


class CoordTransformUI(QtWidgets.QWidget):
    def __init__(self, viewParent):
        super(CoordTransformUI, self).__init__()
        self.setWindowTitle('Recalculate Coordinate System')
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.viewParent = viewParent
        self.ramanctrl: RamanBase = self.viewParent.ramanctrl

        self.imageMarkers: List[ImageMarker] = []  # in the new coord system
        self.newImageMarkers: List[ImageMarker] = []
        self.imageMarkerWidgets: List[CoordinateSystemMarker] = []
        self.trayMarkers: List[TrayMarker] = []  # in the new coord system
        self.newTrayMarkers: List[TrayMarker] = []  # in the new coord system

        self.layout = QtWidgets.QVBoxLayout()
        self.setLayout(self.layout)

        selectionLayout = QtWidgets.QHBoxLayout()
        self.trayMarkersBtn: QtWidgets.QRadioButton = QtWidgets.QRadioButton('Use Tray Markers')
        self.trayMarkersBtn.pressed.connect(self._useTrayMarkers)
        self.trayMarkersBtn.setChecked(True)
        self.imgMarkersBtn: QtWidgets.QRadioButton = QtWidgets.QRadioButton('Use Image Markers')
        self.imgMarkersBtn.pressed.connect(self._useImageMarkers)

        selectionLayout.addWidget(self.trayMarkersBtn)
        selectionLayout.addWidget(self.imgMarkersBtn)

        self.addMarkerBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('Add New Markers')
        self.addMarkerBtn.setStyleSheet("background-color : lightgrey")
        self._formatAsToggleBtn(self.addMarkerBtn)

        self.transferResult: QtWidgets.QLabel = QtWidgets.QLabel('No valid input')

        self.trayMarkerGroup: QtWidgets.QGroupBox = self._getTrayMarkerGroup()
        self.imgMarkerGroup: QtWidgets.QGroupBox = self._getImageMarkerGroup()

        saveBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('Save to Dataset')
        saveBtn.clicked.connect(self._saveToDataset)

        self.layout.addLayout(selectionLayout)
        self.layout.addWidget(self.trayMarkerGroup)
        self.layout.addWidget(self.transferResult)
        self.layout.addWidget(saveBtn)

        self._getMarkersFromDataset()

    def _getMarkersFromDataset(self) -> None:
        if self.viewParent is not None:
            self.trayMarkers = deepcopy(self.viewParent.dataset.trayMarkers)
            self.imageMarkers = deepcopy(self.viewParent.dataset.imageMarkers)
            for index, imgMarker in enumerate(self.imageMarkers):
                pxPos: tuple = (imgMarker.imgCoordX, imgMarker.imgCoordY)
                newMarkerWidget: CoordinateSystemMarker = CoordinateSystemMarker(index, pxPos)
                self.imageMarkerWidgets.append(newMarkerWidget)
                self.viewParent.scene().addItem(newMarkerWidget)

    def _formatAsToggleBtn(self, btn: QtWidgets.QPushButton) -> None:
        btn.setCheckable(True)
        btn.setChecked(False)
        btn.clicked.connect(lambda: self._setBtnColor(btn))

    def _getTrayMarkerGroup(self) -> QtWidgets.QGroupBox:
        layout = QtWidgets.QGridLayout()
        group: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Sample Tray Markers')
        group.setLayout(layout)
        if len(self.trayMarkers) == 0:
            layout.addWidget(QtWidgets.QLabel('No tray markers found.'))
            for i in range(3):
                layout.addWidget(QtWidgets.QLabel('New Marker Placeholder'))
        return group

    def _getImageMarkerGroup(self) -> QtWidgets.QGroupBox:
        def makeCenterOnLambda(ind):
            return lambda: self._centerOnImageMarker(ind)

        def makeDeleteLambda(ind):
            return lambda: self._deleteImageMarker(ind)
        
        def makeReadNewPosLambda(ind):
            return lambda: self._readNewImageMarker(ind)

        layout = QtWidgets.QGridLayout()
        group: QtWidgets.QGroupBox = QtWidgets.QGroupBox('Image Based Markers')
        group.setLayout(layout)
        layout.addWidget(self.addMarkerBtn)
        if len(self.imageMarkers) == 0:
            layout.addWidget(QtWidgets.QLabel('No image markers found.'))
        else:
            layout.addWidget(QtWidgets.QLabel('Number'), 1, 0)
            layout.addWidget(QtWidgets.QLabel('Coordinates old'), 1, 1)
            layout.addWidget(QtWidgets.QLabel('Coordinates new'), 1, 2)

            for index, imgMarker in enumerate(self.imageMarkers):
                # reset indices, as they could have been reordered by deleting a marker..
                imgMarker.index = index
                self.imageMarkerWidgets[index].index = index
                newMarker: ImageMarker = self.newImageMarkers[index]
                newMarker.index = index
                newX, newY, newZ = newMarker.worldCoordX, newMarker.worldCoordY, newMarker.worldCoordZ
                x, y, z = imgMarker.worldCoordX, imgMarker.worldCoordY, imgMarker.worldCoordZ
                row: int = 2+index

                updateBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('Read Coordinates')
                updateBtn.clicked.connect(makeReadNewPosLambda(index))
                focusBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('Center On')
                focusBtn.clicked.connect(makeCenterOnLambda(index))
                delBtn: QtWidgets.QPushButton = QtWidgets.QPushButton('Delete')
                delBtn.clicked.connect(makeDeleteLambda(index))
                layout.addWidget(QtWidgets.QLabel(str(imgMarker.index+1)), row, 0)
                layout.addWidget(QtWidgets.QLabel(f'x: {round(x)} µm\ny: {round(y)} µm\nz: {round(z)} µm'), row, 1)
                if np.nan in [newX, newY, newZ]:
                    layout.addWidget(QtWidgets.QLabel('Coordinates not yet read.'), row, 2)
                else:
                    layout.addWidget(QtWidgets.QLabel(f'x: {round(newX)} µm\ny: {round(newY)} µm\nz: {round(newZ)} µm'), row, 2)
                layout.addWidget(updateBtn, row, 3)
                layout.addWidget(focusBtn, row, 4)
                layout.addWidget(delBtn, row, 5)
        return group

    def _updateTransferResult(self) -> None:
        oldMarkers: list = self.trayMarkers if self.trayMarkersBtn.isChecked() else self.imageMarkers
        newMarkers: list = self.newTrayMarkers if self.trayMarkersBtn.isChecked() else self.newImageMarkers
        srcPoints: np.ndarray = np.array(
            [[marker.worldCoordX, marker.worldCoordY, marker.worldCoordZ] for marker in oldMarkers])
        dstPoints: np.ndarray = np.array(
            [[marker.worldCoordX, marker.worldCoordY, marker.worldCoordZ] for marker in newMarkers])
        hasNan: bool = (np.any(np.isnan(srcPoints)) or np.any(np.isnan(dstPoints)))
        if len(oldMarkers) == len(newMarkers) and len(oldMarkers) >= 3 and not hasNan:
            transformMatrix, pc, zpc, residuals = getTransform(srcPoints, dstPoints)
            self.transferResult.setText(f'Transform residuals (µm): {residuals}')
        else:
            self.transferResult.setText('No valid inputs for coordinate transfer')

    def _setBtnColor(self, btn: QtWidgets.QPushButton):
        """
        Sets color of the toggle button to indicate its status.
        """
        if btn.isChecked():
            btn.setStyleSheet("background-color : lightblue")
        else:
            btn.setStyleSheet("background-color : lightgrey")

    def _useTrayMarkers(self) -> None:
        """
        Use markers on the sample tray that are NOT in the microscope image.
        """
        self.imgMarkerGroup.setParent(None)
        self.trayMarkerGroup.setParent(None)
        self.trayMarkerGroup = self._getTrayMarkerGroup()
        self.layout.insertWidget(1, self.trayMarkerGroup)

    def _useImageMarkers(self) -> None:
        """
        Use markers that are defined through characteristic spots within the microscope image.
        """
        self.imgMarkerGroup.setParent(None)
        self.trayMarkerGroup.setParent(None)
        self.imgMarkerGroup = self._getImageMarkerGroup()
        self.layout.insertWidget(1, self.imgMarkerGroup)
        self._updateTransferResult()

    def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
        if self.addMarkerBtn.isChecked() and event.button() == QtCore.Qt.LeftButton:
            scenePos = self.viewParent.mapToScene(event.pos())
            self._addNewImageMarker((scenePos.x(), scenePos.y()))

    def _deleteImageMarker(self, markerIndex: int) -> None:
        self.imageMarkers.remove(self.imageMarkers[markerIndex])
        self.newImageMarkers.remove(self.newImageMarkers[markerIndex])
        self.viewParent.scene().removeItem(self.imageMarkerWidgets[markerIndex])
        self.imageMarkerWidgets.remove(self.imageMarkerWidgets[markerIndex])
        self._useImageMarkers()

    def _centerOnImageMarker(self, markerIndex: int) -> None:
        self.viewParent.centerOn(self.imageMarkerWidgets[markerIndex])

    def _addNewImageMarker(self, pos: tuple) -> None:
        newImageMarker: ImageMarker = ImageMarker()
        newImageMarker.index = len(self.imageMarkers)
        x, y, z = self.ramanctrl.getPosition()
        newImageMarker.worldCoordX = x
        newImageMarker.worldCoordY = y
        newImageMarker.worldCoordZ = z
        newImageMarker.imgCoordX = pos[0]
        newImageMarker.imgCoordY = pos[1]
        self.imageMarkers.append(newImageMarker)

        newNewImageMarker: ImageMarker = ImageMarker()
        newNewImageMarker.imgCoordX = pos[0]
        newNewImageMarker.imgCoordY = pos[1]
        self.newImageMarkers.append(newNewImageMarker)

        newMarkerWidget: CoordinateSystemMarker = CoordinateSystemMarker(len(self.imageMarkers), pos)
        self.imageMarkerWidgets.append(newMarkerWidget)
        self.viewParent.scene().addItem(newMarkerWidget)
        self._useImageMarkers()

    def _readNewImageMarker(self, index: int) -> None:
        """Reads current instrument coordinates and assignes them to the respective "new image marker" """
        x, y, z = self.ramanctrl.getPosition()
        self.newImageMarkers[index].worldCoordX = x
        self.newImageMarkers[index].worldCoordY = y
        self.newImageMarkers[index].worldCoordZ = z
        self._useImageMarkers()

    def _saveToDataset(self) -> None:
        if self.trayMarkersBtn.isChecked():
            print('saving tray markers to dataset')
        else:
            print('saving image makers to dataset')

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:
        reply = QtWidgets.QMessageBox.question(self, 'Close without saving',
                                               'The window is about to be closed.\nSave markers prior to closing?',
                                               QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                                               QtWidgets.QMessageBox.Yes)
        if reply == QtWidgets.QMessageBox.Yes:
            self._saveToDataset()

        if self.viewParent is not None:
            self.viewParent.showHiddenWidgets()
            self.viewParent.coordTransferWidget = None
        del self


class CoordinateSystemMarker(QtWidgets.QGraphicsItem):
    def __init__(self, index: int, position: tuple):
        super().__init__()
        self.setPos(position[0], position[1])
        self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable)
        self.setCacheMode(QtWidgets.QGraphicsItem.DeviceCoordinateCache)
        self.index = index
        self.pxSize: int = 101
        self.gapSize: int = 10
        # self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges)
        # self.poschanged = False

    def boundingRect(self) -> QtCore.QRectF:
        return QtCore.QRectF(-self.pxSize/2, -self.pxSize/2, self.pxSize, self.pxSize)

    def paint(self, painter: QtGui.QPainter, option, widget) -> None:
        halfSize: int = int(round(self.pxSize / 2))
        halfGapSize: int = int(round(self.gapSize / 2))

        painter.setPen(QtCore.Qt.green)
        painter.setBrush(QtGui.QColor(30, 255, 30, 64))

        painter.drawEllipse(-halfSize, -halfSize, self.pxSize, self.pxSize)

        # horizontal lines
        painter.drawLine(-halfSize, 0, -halfGapSize, 0)
        painter.drawLine(halfGapSize, 0, halfSize, 0)

        # vertical lines
        painter.drawLine(0, -halfSize, 0, -halfGapSize)
        painter.drawLine(0, halfGapSize, 0, halfSize)

        painter.drawText(-halfSize, -halfSize, str(f'Marker {self.index+1}'))


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    coordUI = CoordTransformUI(None)
    coordUI.show()
    ret = app.exec_()