analysisview.py 30 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
#!/usr/bin/env python3
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
"""
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, QtGui, QtWidgets
24
import numpy as np
JosefBrandt's avatar
 
JosefBrandt committed
25 26
import sys

27 28 29 30 31

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

JosefBrandt's avatar
 
JosefBrandt committed
32 33
from .analysiswidgets import ExpExcelDialog
from .analysisplots import TypeHistogramView, SpectraPlot
34
from .loadresults import LoadWITecResults
35
from .particleeditor import ParticleEditor
36
from .database import DataBaseWindow
JosefBrandt's avatar
 
JosefBrandt committed
37 38
from .colorlegend import ColorHandler

Hackmet's avatar
Hackmet committed
39
try:
40
    from .sqlexport import SQLExport
Hackmet's avatar
Hackmet committed
41 42 43
    sqlEnabled = True
except:
    sqlEnabled = False
44 45


Hackmet's avatar
Hackmet committed
46
class ParticleAnalysis(QtWidgets.QMainWindow):
47 48
    def __init__(self, dataset, parent=None):
        super(ParticleAnalysis, self).__init__(parent)
49 50 51
        self.setGeometry(100, 100, 1680, 1050)
        self.setWindowTitle('Results of polymer analysis')
        self.layout = QtWidgets.QHBoxLayout()
Hackmet's avatar
Hackmet committed
52 53 54 55
        self.widget = QtWidgets.QWidget()
        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)
        
56
        self.parent = parent
JosefBrandt's avatar
JosefBrandt committed
57 58
        self.dataset = dataset
        self.particleContainer = dataset.particleContainer
JosefBrandt's avatar
 
JosefBrandt committed
59
        self.editor = ParticleEditor(self.particleContainer, self)
JosefBrandt's avatar
 
JosefBrandt committed
60
        self.colorHandler = ColorHandler()
61
        
JosefBrandt's avatar
JosefBrandt committed
62
#        self.additivePlot = None
63
        self.importWindow = None
64
        
65 66 67 68 69
        self.polymerCheckBoxes = []
        self.lastSelectedCheckBoxNames = []
        
        self.currentParticleIndex = 0
        self.currentSpectrumIndex = 0
JosefBrandt's avatar
 
JosefBrandt committed
70
#        self.lastSpectrumInFocus = None
71
        
JosefBrandt's avatar
 
JosefBrandt committed
72
        self.typeHistogramPlot = TypeHistogramView(self)
JosefBrandt's avatar
JosefBrandt committed
73
#        self.typeHistogramPlot.indexClicked.connect(self.getAdditivePlot)
74 75 76 77 78 79 80 81 82
        self.sizeHistogramCanvas = FigureCanvas(Figure())
       
        sizeHistGroup = QtWidgets.QGroupBox()
        sizeHistLayout = QtWidgets.QHBoxLayout()
        self.sizeHist_ax = self.sizeHistogramCanvas.figure.subplots()
        self.sizeHist_ax.axis('off')
        self.sizeHistogramCanvas.figure.subplots_adjust(left=0.1, top=0.93, bottom=0.15, right=0.995)
        histNavigation = NavigationToolbar(self.sizeHistogramCanvas, self)
        histNavigation.setOrientation(QtCore.Qt.Vertical)
Hackmet's avatar
Hackmet committed
83
        histNavigation.setFixedWidth(50)
84 85 86 87
        sizeHistLayout.addWidget(histNavigation)
        sizeHistLayout.addWidget(self.sizeHistogramCanvas)
        sizeHistGroup.setLayout(sizeHistLayout)
        
JosefBrandt's avatar
 
JosefBrandt committed
88
        self.specPlot = SpectraPlot(self.dataset)
89 90
        
        splitter1 = QtWidgets.QSplitter(QtCore.Qt.Vertical)
JosefBrandt's avatar
 
JosefBrandt committed
91
        splitter1.addWidget(self.specPlot)
92 93 94
        splitter1.addWidget(sizeHistGroup)
        splitter2 = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
        splitter2.addWidget(splitter1)
JosefBrandt's avatar
JosefBrandt committed
95
        splitter2.addWidget(self.typeHistogramPlot)
96 97
        splitter2.setSizes([300, 150])
       
JosefBrandt's avatar
 
JosefBrandt committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        referenceGroup = QtWidgets.QGroupBox('Reference Spectra')
        referenceLayout = QtWidgets.QHBoxLayout()
        
        self.refSelector = QtWidgets.QComboBox()
        self.refSelector.setMinimumWidth(200)
        self.refSelector.setDisabled(True)
        self.dbWin = DataBaseWindow(self)
        self.dbWin.selectDataBase(refreshParent=True)  #this includes updating the refSelector
        
        self.refSelector.currentIndexChanged.connect(self.updateSpecPlot)
        referenceLayout.addWidget(QtWidgets.QLabel('Select Reference'))
        referenceLayout.addWidget(self.refSelector)
        referenceLayout.addStretch()
        referenceGroup.setLayout(referenceLayout)
        

114 115 116
        self.navigationGroup = QtWidgets.QGroupBox('Navigate through polymers')
        self.navigationGroup.setDisabled(True)
        navigationLayout = QtWidgets.QHBoxLayout()
JosefBrandt's avatar
 
JosefBrandt committed
117 118 119
        self.typeSelectorCombo = QtWidgets.QComboBox()
        self.typeSelectorCombo.currentIndexChanged.connect(self.displayNewPolymerType)
        self.typeSelectorCombo.setMinimumWidth(150)
120
        self.particleSelector = QtWidgets.QSpinBox()
JosefBrandt's avatar
 
JosefBrandt committed
121 122 123
        self.particleSelector.valueChanged.connect(self.updateParticleSelection)
        self.particleNumberLabel = QtWidgets.QLabel('of xx particles; ')
        
124 125
        self.spectrumSelector = QtWidgets.QSpinBox()
        self.spectrumSelector.valueChanged.connect(self.selectSpectrum)
JosefBrandt's avatar
 
JosefBrandt committed
126
        self.spectrumNumberLabel = QtWidgets.QLabel('of xx spectra')
127 128 129 130 131 132
        for spinbox in [self.particleSelector, self.spectrumSelector]:
            spinbox.setMinimum(1)
            spinbox.setSingleStep(1)
            spinbox.setValue(1)
        
        navigationLayout.addWidget(QtWidgets.QLabel('Select Polymer Type:'))
JosefBrandt's avatar
 
JosefBrandt committed
133
        navigationLayout.addWidget(self.typeSelectorCombo)
134 135 136
        navigationLayout.addStretch()
        navigationLayout.addWidget(QtWidgets.QLabel('Select Particle'))
        navigationLayout.addWidget(self.particleSelector)
JosefBrandt's avatar
 
JosefBrandt committed
137 138
        navigationLayout.addWidget(self.particleNumberLabel)
        navigationLayout.addStretch()
139 140
        navigationLayout.addWidget(QtWidgets.QLabel('Select Spectrum'))
        navigationLayout.addWidget(self.spectrumSelector)
JosefBrandt's avatar
 
JosefBrandt committed
141 142
        navigationLayout.addWidget(self.spectrumNumberLabel)
#        navigationLayout.addStretch()
143 144 145 146 147
        
        self.navigationGroup.setLayout(navigationLayout)
        
        topLayout = QtWidgets.QHBoxLayout()
        topLayout.addWidget(self.navigationGroup)
Hackmet's avatar
Hackmet committed
148
        topLayout.addWidget(referenceGroup)
149
        
JosefBrandt's avatar
 
JosefBrandt committed
150
        viewLayout = QtWidgets.QVBoxLayout()
151 152 153 154 155 156 157 158
        viewLayout.addLayout(topLayout)
        viewLayout.addWidget(splitter2)
        viewLayout.setStretch(1, 1)

        self.optionsGroup = QtWidgets.QGroupBox('Further Options')
        optionsLayout = QtWidgets.QFormLayout()
        
        self.hqiSpinBox = QtWidgets.QDoubleSpinBox()
JosefBrandt's avatar
 
JosefBrandt committed
159
        self.hqiSpinBox.setValue(self.dataset.resultParams['minHQI'])
160 161
        self.hqiSpinBox.setDecimals(1)
        self.hqiSpinBox.setMinimum(0)
JosefBrandt's avatar
JosefBrandt committed
162
        self.hqiSpinBox.setMaximum(100)
JosefBrandt's avatar
 
JosefBrandt committed
163 164
        self.hqiSpinBox.setMaximumWidth(100)
        self.hqiSpinBox.valueChanged.connect(self.applyHQIThresholdToResults)
165 166
        optionsLayout.addRow(QtWidgets.QLabel('min HQI:'), self.hqiSpinBox)
        
JosefBrandt's avatar
JosefBrandt committed
167 168 169 170 171 172
#        self.compHqiSpinBox = QtWidgets.QDoubleSpinBox()
#        self.compHqiSpinBox.setValue(30.0)
#        self.compHqiSpinBox.setDecimals(1)
#        self.compHqiSpinBox.setMinimum(0)
#        self.compHqiSpinBox.setDisabled(True)
#        optionsLayout.addRow(QtWidgets.QLabel('min component HQI'), self.compHqiSpinBox)
173 174 175 176
        
        self.dispResultSpinBox = QtWidgets.QSpinBox()
        self.dispResultSpinBox.setValue(20)
        self.dispResultSpinBox.setMinimum(1)
JosefBrandt's avatar
 
JosefBrandt committed
177
        self.dispResultSpinBox.setMaximumWidth(100)
JosefBrandt's avatar
JosefBrandt committed
178
        self.dispResultSpinBox.valueChanged.connect(self.updateHistograms)
179 180 181 182 183
        optionsLayout.addRow(QtWidgets.QLabel('Max. items in display:'), self.dispResultSpinBox)
        
        
        self.optionsGroup.setLayout(optionsLayout)
        self.optionsGroup.setMinimumWidth(175)
JosefBrandt's avatar
JosefBrandt committed
184
#        self.optionsGroup.setDisabled(True)
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        
        self.resultScrollarea = QtWidgets.QScrollArea(self)
        self.resultScrollarea.setFixedWidth(250)
        self.resultScrollarea.setWidgetResizable(True)

        widget = QtWidgets.QWidget()
        self.resultScrollarea.setWidget(widget)
        self.layout_SArea = QtWidgets.QVBoxLayout(widget)

        self.resultCheckBoxes = QtWidgets.QGroupBox('Display Polymer Types:')
        self.resultCheckBoxesLayout = QtWidgets.QVBoxLayout()
        self.showTotalSelector = QtWidgets.QCheckBox('Show Total Distribution')
        self.showTotalSelector.setChecked(True)
        self.showTotalSelector.setDisabled(True)
        self.resultCheckBoxesLayout.addWidget(self.showTotalSelector)
       
        self.resultCheckBoxesLayout.addStretch()
        self.resultCheckBoxes.setLayout(self.resultCheckBoxesLayout)

        self.layout_SArea.addWidget(self.resultCheckBoxes)
JosefBrandt's avatar
 
JosefBrandt committed
205 206
        
        self.menuLayout = QtWidgets.QVBoxLayout()
207 208 209 210 211 212
        self.menuLayout.addWidget(self.optionsGroup)
        self.menuLayout.addWidget(self.resultScrollarea)
        
        self.layout.addLayout(self.menuLayout)
        self.layout.addLayout(viewLayout)
        
JosefBrandt's avatar
JosefBrandt committed
213 214
        minHQI = self.dataset.resultParams['minHQI']
#        compHQI = self.dataset.resultParams['compHQI']
Lars Bittrich's avatar
Lars Bittrich committed
215 216
        if minHQI is not None:
            self.hqiSpinBox.setValue(minHQI)
JosefBrandt's avatar
JosefBrandt committed
217
#            self.compHqiSpinBox.setValue(compHQI)
218
         
Hackmet's avatar
Hackmet committed
219 220
        self.createActions()
        self.createMenus()
JosefBrandt's avatar
JosefBrandt committed
221
        self.applyHQIThresholdToResults()
JosefBrandt's avatar
 
JosefBrandt committed
222 223 224 225 226 227
        self.createHistogramData()
        self.updateHistograms()
        self.initializeSpecPlot()
        self.displayNewPolymerType()
        self.updateParticleSelection()
#        self.createPolymerOverlay()
Hackmet's avatar
Hackmet committed
228 229 230 231 232 233 234 235 236 237 238 239
    
    def createActions(self):
        self.loadTrueMatchAct = QtWidgets.QAction("Load &TrueMatch Results", self)
        self.loadTrueMatchAct.triggered.connect(self.importTrueMatchResults)
        
        self.loadTextFileAct = QtWidgets.QAction("Load &ordered Text File", self)
        self.loadTextFileAct.setDisabled(True)
        
        self.noOverlayAct = QtWidgets.QAction("&No Overlay", self)
        self.selOverlayAct = QtWidgets.QAction("&Selected Overlay", self)
        self.fullOverlayAct = QtWidgets.QAction("&Full Overlay", self)
        
JosefBrandt's avatar
JosefBrandt committed
240
        self.transpAct = QtWidgets.QAction("&Transparent Overlay", self)
Hackmet's avatar
Hackmet committed
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
        self.transpAct.triggered.connect(self.createPolymerOverlay)
            
        self.hideLabelAct = QtWidgets.QAction('&Hide Polymer Numbers', self)
        self.hideLabelAct.triggered.connect(self.show_hide_labels)
        
        self.darkenAct = QtWidgets.QAction("&Darken Image", self)
        self.darkenAct.triggered.connect(self.darkenBackground)
        
        for act in [self.noOverlayAct, self.selOverlayAct, self.fullOverlayAct, self.hideLabelAct, self.transpAct, self.darkenAct]:
            act.setCheckable(True)
        self.fullOverlayAct.setChecked(True)
        
        self.seedAct = QtWidgets.QAction("&Set Color Seed", self)
        self.seedAct.triggered.connect(self.updateColorSeed)

        self.databaseAct = QtWidgets.QAction("&ManageDatabase", self)
        self.databaseAct.triggered.connect(self.launchDBManager)
        
        self.expExcelAct= QtWidgets.QAction("Export &Excel List", self)
        self.expExcelAct.setDisabled(True)
        self.expExcelAct.triggered.connect(self.exportToExcel)
        
        self.expSQLAct = QtWidgets.QAction("Export to &SQL Database", self)
        self.expSQLAct.setDisabled(True)
        self.expSQLAct.triggered.connect(self.exportToSQL)
    
    def createMenus(self):
        self.importMenu = QtWidgets.QMenu("&Import Results")
        self.importMenu.addActions([self.loadTrueMatchAct, self.loadTextFileAct])
        
        self.dispMenu = QtWidgets.QMenu("&Display", self)
        self.overlayActGroup = QtWidgets.QActionGroup(self.dispMenu)
        self.overlayActGroup.setExclusive(True)
        self.overlayActGroup.triggered.connect(self.createPolymerOverlay)
JosefBrandt's avatar
JosefBrandt committed
275
        self.overlayActGroup.triggered.connect(self.updateHistograms)
Hackmet's avatar
Hackmet committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        
        for act in [self.noOverlayAct, self.selOverlayAct, self.fullOverlayAct]:
            self.dispMenu.addAction(act)
            self.overlayActGroup.addAction(act)
        
        self.dispMenu.addSeparator()
        self.dispMenu.addActions([self.transpAct, self.hideLabelAct, self.darkenAct, self.seedAct])
        
        self.refMenu = QtWidgets.QMenu("&References")
        self.refMenu.addAction(self.databaseAct)
        
        self.exportMenu = QtWidgets.QMenu("&Export", self)
        self.exportMenu.addAction(self.expExcelAct)
        self.exportMenu.addAction(self.expSQLAct)
        
        self.menuBar().addMenu(self.importMenu)
        self.menuBar().addMenu(self.dispMenu)
        self.menuBar().addMenu(self.refMenu)
        self.menuBar().addMenu(self.exportMenu)
JosefBrandt's avatar
 
JosefBrandt committed
295
        
Hackmet's avatar
Hackmet committed
296 297 298 299 300 301 302 303 304 305 306
    def launchDBManager(self):
        if self.dbWin.isHidden():
            self.dbWin.show()
    
    def populateRefSelector(self):
        #delete all present entries:
        self.refSelector.clear()
        
        if self.dbWin.activeDatabase is None:
            self.refSelector.setDisabled(True)
        else:
Hackmet's avatar
Hackmet committed
307
            self.refSelector.addItem('')
Hackmet's avatar
Hackmet committed
308 309 310 311
            self.refSelector.addItems(self.dbWin.activeDatabase.spectraNames)
            self.refSelector.setDisabled(False)
            
    def importTrueMatchResults(self):
JosefBrandt's avatar
 
JosefBrandt committed
312
        self.importWindow = LoadWITecResults(self.particleContainer, self)
313
        self.importWindow.exec()
314
    
JosefBrandt's avatar
JosefBrandt committed
315 316 317 318 319 320 321 322
#    @QtCore.pyqtSlot(int)
#    def getAdditivePlot(self, clickedindex):
#        polymer = self.datastats.typehistogram[clickedindex][0]        #get the polymer name, that was clicked on
#      
#        if self.datastats.sorted_additives is not None and \
#           len(self.datastats.sorted_additives[clickedindex]) > 0:            
#            self.additivePlot = AdditiveViewer(polymer, self.datastats.sorted_additives[clickedindex])
#            self.additivePlot.show()
323
    
324
    @QtCore.pyqtSlot()
JosefBrandt's avatar
JosefBrandt committed
325
    def applyHQIThresholdToResults(self):
JosefBrandt's avatar
 
JosefBrandt committed
326 327 328 329
        hqi = self.hqiSpinBox.value()
        self.particleContainer.applyHQITresholdToParticles(hqi)
        self.dataset.resultParams['minHQI'] = hqi
        self.dataset.save()
JosefBrandt's avatar
JosefBrandt committed
330
        self.createHistogramData()
JosefBrandt's avatar
 
JosefBrandt committed
331 332
        self.updateHistograms()
        
JosefBrandt's avatar
JosefBrandt committed
333 334 335 336 337 338 339 340 341 342
        
#    def formatResults(self):
#        if self.datastats.spectraResults is not None:
#            print('formatResults')
#            self.optionsGroup.setDisabled(False)
#            
#            self.datastats.formatResults(self.hqiSpinBox.value(), self.compHqiSpinBox.value())
#            
#            if self.datastats.additiveResults is not None:
#                self.compHqiSpinBox.setDisabled(False)
Hackmet's avatar
Hackmet committed
343 344
            
            
345 346
            
    def createHistogramData(self):
JosefBrandt's avatar
JosefBrandt committed
347 348 349 350
#        if not self.datastats.createHistogramData():
#            QtWidgets.QMessageBox.critical(self, 'Error', 'Inconsistent particle data. Please restore backup!')
#            return
#        self.particleContainer.updateTypeHistogram()
351 352 353 354 355 356 357 358 359 360 361 362
        
        ###Handle Checkboxes for all polymers...
        self.menuLayout.removeWidget(self.resultScrollarea)
        for i in [self.resultCheckBoxes, self.resultCheckBoxesLayout, self.resultScrollarea, self.layout_SArea]:
            i.setParent(None)
            del i

        for i in self.polymerCheckBoxes:        #remove present boxlabels
            i.setParent(None)
            del i
        self.showTotalSelector.setParent(None)
        self.showTotalSelector.setDisabled(False)
JosefBrandt's avatar
JosefBrandt committed
363
        self.showTotalSelector.stateChanged.connect(self.updateHistograms)
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        
        del self.resultCheckBoxes
        del self.resultCheckBoxesLayout
        del self.resultScrollarea
        del self.layout_SArea
        
        self.resultScrollarea = QtWidgets.QScrollArea(self)
        self.resultScrollarea.setFixedWidth(250)
        self.resultScrollarea.setWidgetResizable(True)
        widget = QtWidgets.QWidget()
        self.resultScrollarea.setWidget(widget)
        self.layout_SArea = QtWidgets.QVBoxLayout(widget)
        self.resultCheckBoxes = QtWidgets.QGroupBox('Show Polymer Types:')
        self.resultCheckBoxesLayout = QtWidgets.QVBoxLayout()
        self.resultCheckBoxesLayout.addWidget(self.showTotalSelector)
JosefBrandt's avatar
JosefBrandt committed
379
        
380
        #generate new checkboxes 
JosefBrandt's avatar
 
JosefBrandt committed
381
        self.polymerCheckBoxes = []#
JosefBrandt's avatar
JosefBrandt committed
382
        uniquePolymers = self.particleContainer.getUniquePolymers()
383
        for index, polymer in enumerate(uniquePolymers):
384 385 386 387 388 389
            self.polymerCheckBoxes.append(QtWidgets.QCheckBox(self))
            self.polymerCheckBoxes[index].setText(polymer)
            self.resultCheckBoxesLayout.addWidget(self.polymerCheckBoxes[index])
            if polymer in self.lastSelectedCheckBoxNames:
                self.polymerCheckBoxes[index].setChecked(True)
            
JosefBrandt's avatar
JosefBrandt committed
390
            self.polymerCheckBoxes[index].stateChanged.connect(self.updateHistograms)
391 392 393 394 395 396 397
            self.polymerCheckBoxes[index].stateChanged.connect(self.createPolymerOverlay)

        self.resultCheckBoxesLayout.addStretch()
        self.resultCheckBoxes.setLayout(self.resultCheckBoxesLayout)
        self.layout_SArea.addWidget(self.resultCheckBoxes)
        self.menuLayout.addWidget(self.resultScrollarea)
        
Hackmet's avatar
Hackmet committed
398 399 400
        self.expExcelAct.setDisabled(False)
        if sqlEnabled:
            self.expSQLAct.setDisabled(False)
401 402
        
        self.navigationGroup.setEnabled(True)
JosefBrandt's avatar
 
JosefBrandt committed
403 404 405 406
        self.typeSelectorCombo.currentIndexChanged.disconnect()
        self.typeSelectorCombo.clear()
        self.typeSelectorCombo.addItems(uniquePolymers)
        self.typeSelectorCombo.currentIndexChanged.connect(self.displayNewPolymerType)
Hackmet's avatar
Hackmet committed
407
                
JosefBrandt's avatar
 
JosefBrandt committed
408 409 410 411 412 413 414 415
        self.polymerIndex = self.typeSelectorCombo.currentIndex()
#        if self.lastSpectrumInFocus is not None:
#            self.currentSpectrumIndex = self.lastSpectrumInFocus
#            self.displayNewPolymerType(resetCurrentIndex=False)
#            print('displaying new type without resetting index')
#        else:
#            print('displaying new type with resetting index')
#            self.displayNewPolymerType()
Hackmet's avatar
Hackmet committed
416
            
417
    
Hackmet's avatar
Hackmet committed
418
    def exportToExcel(self):
JosefBrandt's avatar
 
JosefBrandt committed
419
        expWin = ExpExcelDialog(self.particleContainer, self)
420
        expWin.exec()
Hackmet's avatar
Hackmet committed
421 422
            
    def exportToSQL(self):
JosefBrandt's avatar
 
JosefBrandt committed
423
        sqlexp = SQLExport(self.particleContainer, self)
424
        sqlexp.exec()
JosefBrandt's avatar
 
JosefBrandt committed
425 426 427 428
    
    def initializeSpecPlot(self):
        self.specPlot.loadSpectraAndInitializeSpecPlot()
        self.updateSpecPlot()
429
    
Hackmet's avatar
Hackmet committed
430
    def updateSpecPlot(self, centerOn=True, highlightContour=True):
JosefBrandt's avatar
 
JosefBrandt committed
431 432 433 434 435 436 437
        particleSize = self.particleContainer.getSizeOfParticleByIndex(self.currentParticleIndex)
        hqi = self.particleContainer.getHQIOfSpectrumIndex(self.currentSpectrumIndex)
        self.specPlot.updateParticleSpectrum(self.currentSpectrumIndex, particleSize, hqi)
        self.parent.centerOnRamanIndex(self.currentSpectrumIndex, centerOn=centerOn, highlightContour=highlightContour)  #TODO: is this reasonable to do in that way???
        self.parent.highLightRamanIndex(self.currentSpectrumIndex)
#        self.lastSpectrumInFocus = self.currentSpectrumIndex
            
Hackmet's avatar
Hackmet committed
438 439 440
        if self.refSelector.isEnabled() and self.refSelector.currentText() != '':
            refID = self.dbWin.activeDatabase.spectraNames.index(self.refSelector.currentText())
            ref = self.dbWin.activeDatabase.spectra[refID]
JosefBrandt's avatar
 
JosefBrandt committed
441
            self.specPlot.updateReferenceSpectrum(ref[:, 0], ref[:, 1])
442 443
        
    def selectContour(self, index, centerOn=True):
JosefBrandt's avatar
 
JosefBrandt committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        print('select Contour in analysisview not yet refactored')
#        uniquePolymers = self.particleContainer.getUniquePolymers()
#        if uniquePolymers is not None:
#            #the index is the contour index, find particle index:
#            specIndex = self.datastats.particles2spectra[index][0]  #select first spectrum of partoicle
#            self.currentParticleIndex = index
#            self.currentSpectrumIndex = specIndex
#            
#            selectedPolymer = self.datastats.currentPolymers[specIndex]
#            try:
#                self.polymerIndex = uniquePolymers.index(selectedPolymer)
#            except:
#                print(selectedPolymer)
#                raise
#            
#            #subparticleIndex
#            partIndicesOfThatPolymer = self.datastats.indices[self.polymerIndex]
#            subPartInd = partIndicesOfThatPolymer.index(index)
#            
#            #disconnect analysis widgets:
#            self.particleSelector.valueChanged.disconnect()
#            self.spectrumSelector.valueChanged.disconnect()
JosefBrandt's avatar
 
JosefBrandt committed
466
#            self.typeSelectorCombo.currentIndexChanged.disconnect()
JosefBrandt's avatar
 
JosefBrandt committed
467 468 469 470 471 472 473 474 475 476
#            
#            #set widgets...
#            self.particleSelector.setValue(subPartInd+1)
#            self.particleSelector.setMaximum(len(partIndicesOfThatPolymer))
#            
#            self.spectrumSelector.setValue(1)
#            self.spectrumSelector.setMaximum(len(self.datastats.particles2spectra[index]))
#            
#            selectedPolymer = self.datastats.currentPolymers[specIndex]
#            self.polymerIndex = uniquePolymers.index(selectedPolymer)
JosefBrandt's avatar
 
JosefBrandt committed
477
#            self.typeSelectorCombo.setCurrentIndex(self.polymerIndex)
JosefBrandt's avatar
 
JosefBrandt committed
478 479
#           
#            #reconnect all widgets:
JosefBrandt's avatar
 
JosefBrandt committed
480
#            self.particleSelector.valueChanged.connect(self.updateParticleSelection)
JosefBrandt's avatar
 
JosefBrandt committed
481
#            self.spectrumSelector.valueChanged.connect(self.selectSpectrum)
JosefBrandt's avatar
 
JosefBrandt committed
482
#            self.typeSelectorCombo.currentIndexChanged.connect(self.displayNewPolymerType)
JosefBrandt's avatar
 
JosefBrandt committed
483 484
#            
#            self.updateSpecPlot(centerOn=centerOn)
485 486
    
    def displayNewPolymerType(self, resetCurrentIndex=True):
JosefBrandt's avatar
 
JosefBrandt committed
487 488 489 490 491 492 493 494 495 496 497 498
        polymerName = self.typeSelectorCombo.currentText()
        numParticles = self.particleContainer.getNumberOfParticlesOfAssignment(polymerName)
        self.particleSelector.setMaximum(numParticles)
        self.particleNumberLabel.setText(f'of {numParticles} Particles; ')
        
        self.particleSelector.setValue(1)
        self.spectrumSelector.setValue(1)
        
        self.currentParticleIndex = self.getParticleIndexFromParticleSelector()
        self.spectrumSelector.setMaximum(self.particleContainer.getNumberOfSpectraOfParticle(self.currentParticleIndex))
        self.currentSpectrumIndex = self.getSpectrumIndexFromSpectrumSelector()
        self.updateSpecPlot(centerOn=False)
499
    
JosefBrandt's avatar
 
JosefBrandt committed
500 501 502 503 504 505 506
    def updateParticleSelection(self, resetSpectrumCount=True):
        polymerName = self.typeSelectorCombo.currentText()
        if polymerName != '':
            self.currentParticleIndex = self.getParticleIndexFromParticleSelector()
            numSpectra = self.particleContainer.getNumberOfSpectraOfParticle(self.currentParticleIndex)
            self.spectrumSelector.setMaximum(numSpectra)
            self.spectrumNumberLabel.setText(f'of {numSpectra} Spectra')
507 508
            if resetSpectrumCount:
                self.spectrumSelector.setValue(1)
JosefBrandt's avatar
 
JosefBrandt committed
509 510
            
            self.currentSpectrumIndex = self.getSpectrumIndexFromSpectrumSelector()
Hackmet's avatar
Hackmet committed
511
            self.updateSpecPlot()
512 513
    
    def selectSpectrum(self):
JosefBrandt's avatar
 
JosefBrandt committed
514 515 516 517 518 519 520 521 522 523 524 525 526
        self.currentSpectrumIndex = self.getSpectrumIndexFromSpectrumSelector()
        self.updateSpecPlot()
        
    def getSpectrumIndexFromSpectrumSelector(self):
        specIndicesOfParticle = self.particleContainer.getSpectraIndicesOfParticle(self.currentParticleIndex)
        try:
            return specIndicesOfParticle[self.spectrumSelector.value()-1]
        except IndexError:
            print(f'requested specIndex {self.spectrumSelector.value()-1} for particle Index {self.currentParticleIndex} of specIndices: {specIndicesOfParticle}')
    
    def getParticleIndexFromParticleSelector(self):
        particleIndicesOfType = self.particleContainer.getIndicesOfParticleType(self.typeSelectorCombo.currentText())
        return particleIndicesOfType[self.particleSelector.value()-1]
527
    
JosefBrandt's avatar
JosefBrandt committed
528 529 530 531 532
    def updateHistograms(self):  
        self.updateTypeHistogram()
        self.updateSizeHistogram()
        
    def updateTypeHistogram(self):
533 534
        #draw the general histogram
        colorList = []
535 536
        abundancyList = []
        labelList = []
JosefBrandt's avatar
JosefBrandt committed
537 538
        typeHistogram = self.particleContainer.getTypeHistogram()
        for index, polymType in enumerate(typeHistogram):
Hackmet's avatar
Hackmet committed
539
            if not self.selOverlayAct.isChecked() or self.polymerCheckBoxes[index].isChecked():
JosefBrandt's avatar
 
JosefBrandt committed
540 541
                text = f'{typeHistogram[polymType]} x {polymType}'
                labelList.append(text)
JosefBrandt's avatar
JosefBrandt committed
542
                abundancyList.append(typeHistogram[polymType])
JosefBrandt's avatar
 
JosefBrandt committed
543
                curColor = self.colorHandler.getColorFromName(self.dataset.colorSeed, polymType)
544
                colorList.append(QtGui.QColor(*curColor))
545
            
JosefBrandt's avatar
JosefBrandt committed
546 547 548 549 550 551
#        print("abundancyList:", abundancyList)
#        print("labelList:", labelList)
#        print("colorList:", colorList)
        self.typeHistogramPlot.updateTypeHistogram(list(zip(abundancyList, labelList, colorList)))
    
    def updateSizeHistogram(self):
JosefBrandt's avatar
 
JosefBrandt committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        if self.particleContainer.getNumberOfParticles() > 0:
            #general size histogram
            self.sizeHist_ax.clear()
            self.sizeHist_ax.axis('on')
    
            self.bins = np.logspace(0.1, 3, 20)
            self.sizes = self.particleContainer.getSizesOfAllParticles()
                
    #        self.sizes = [i[0] if np.isnan(i[2]) else i[2] for i in self.datastats.getParticleStats()]      #extract long size (if ellipse fit is nan -> box fit)
            sizehist = np.histogram(self.sizes, self.bins)
            self.totalhistx = []
            for i in range(19):
                self.totalhistx.append(np.mean((sizehist[1][i], sizehist[1][i+1])))
            self.totalhisty = sizehist[0]
            
            self.sizeHist_ax.tick_params(axis='both', which='both', labelsize=15)
            self.sizeHist_ax.set_xlabel('Size (µm)', fontsize = 15)
            self.sizeHist_ax.set_ylabel('Number', fontsize = 15)
            self.sizeHist_ax.set_xlim(3, 1100)        
            self.sizeHist_ax.figure.canvas.draw()
            
            if self.showTotalSelector.isChecked():
                self.sizeHist_ax.semilogx(self.totalhistx, self.totalhisty, label = 'total')
                
            #get selected boxes
            selectedTypes = []
            for checkbox in self.polymerCheckBoxes:
                if checkbox.isChecked() == True:
                    selectedTypes.append(checkbox.text())
            
            for polymType in selectedTypes:
                sizes = self.particleContainer.getSizesOfParticleType(polymType)
    #            sizes = [self.sizes[index] for index in range(len(self.sizes)) 
    #                        if self.datastats.currentPolymers[index] == i]
                sizehist = np.histogram(sizes, self.bins)
                color = self.colorHandler.getColorFromName(self.dataset.colorSeed, polymType, base255=False)
                self.sizeHist_ax.semilogx(self.totalhistx, sizehist[0], label=polymType, color=color)    
            
            self.sizeHist_ax.legend(prop = {'size': 15})
            self.sizeHist_ax.tick_params(axis='both', which='both', labelsize=15)
            self.sizeHist_ax.set_xlabel('Size (µm)', fontsize = 15)
            self.sizeHist_ax.set_ylabel('Number', fontsize = 15)
            self.sizeHist_ax.set_xlim(3, 1100)        
            self.sizeHist_ax.figure.canvas.draw()
            
            self.lastSelectedCheckBoxNames = [checkbox.text() for checkbox in self.polymerCheckBoxes if checkbox.isChecked()]
598 599 600
            
     
    def darkenBackground(self):
Hackmet's avatar
Hackmet committed
601
        self.parent.darkenPixmap = self.darkenAct.isChecked()
602
        
Hackmet's avatar
Hackmet committed
603
        if self.darkenAct.isChecked():
604 605 606 607 608 609 610
            self.parent.scene().setBackgroundBrush(QtGui.QColor(5, 5, 5))
            self.parent.item.setOpacity(0.2)
        else:
            self.parent.scene().setBackgroundBrush(QtCore.Qt.darkGray)
            self.parent.item.setOpacity(1)

    def updateColorSeed(self):
JosefBrandt's avatar
 
JosefBrandt committed
611
        text, ok = QtWidgets.QInputDialog.getText(self, 'Color Seed', 'Enter New Seed here', text=self.dataset.colorSeed)
612
        if ok:
JosefBrandt's avatar
 
JosefBrandt committed
613 614
            self.dataset.colorSeed = text
#            self.datastats.dataset.colorSeed = text
JosefBrandt's avatar
JosefBrandt committed
615
            self.updateHistograms()
616 617 618
            self.createPolymerOverlay()
    
    def createPolymerOverlay(self):  
JosefBrandt's avatar
 
JosefBrandt committed
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
        pass   #REFACTOR TO INDIVIDUAL CONTOUR ITEMS
##        uniquePolymers = self.datastats.getUniquePolymers()
#        uniquePolymers = self.particleContainer.getUniquePolymers()
##        if not self.noOverlayAct.isChecked() and self.datastats.indices is not None:
#        if not self.noOverlayAct.isChecked():
##            if len(self.datastats.indices) > 0:
#            
#            alpha = (128 if self.transpAct.isChecked() else 255)
#            #get colors for each polymer type
#            colorList = [QtGui.QColor(255, 255, 255, alpha=50)]*len(self.datastats.particleResults)
#            legendItems = []
#                
#            for index, indexList in enumerate(self.datastats.indices):
#                if self.fullOverlayAct.isChecked() or (self.selOverlayAct.isChecked() and self.polymerCheckBoxes[index].isChecked()):
#                    
#                    color = self.colorHandler.getColorFromName(self.dataset.colorSeed, uniquePolymers[index])
##                        color = self.getColorFromName(uniquePolymers[index], base255=True)
#                    color = QtGui.QColor(color[0], color[1], color[2], alpha=alpha)
#                    legendItems.append((uniquePolymers[index], color))
#                    for i in indexList:
#                        colorList[i] = color
#            
#            self.parent.contouritem.colorList = colorList
#            self.parent.contouritem.update()
#            
#            self.parent.imparent.legend.setTextColorItems(legendItems)
#            self.parent.imparent.legend.show()
#            
#        else:
#            self.parent.contouritem.colorList = []
#            self.parent.contouritem.update()
#            self.parent.imparent.legend.setTextColorItems([])
#            self.parent.imparent.legend.hide()
652 653
            
    def show_hide_labels(self):
Hackmet's avatar
Hackmet committed
654
        hidden = self.hideLabelAct.isChecked()
655 656 657
        for scanIndicator in self.parent.ramanscanitems:
            scanIndicator.hidden = hidden
            scanIndicator.update()
Hackmet's avatar
Hackmet committed
658

659 660
    
    def closeEvent(self, event):
JosefBrandt's avatar
 
JosefBrandt committed
661
        for window in [self.importWindow, self.dbWin]:
662 663
            try: window.close()
            except: pass
Hackmet's avatar
Hackmet committed
664
        self.parent.imparent.particelAnalysisAct.setChecked(False)
665 666 667 668
        event.accept()


if __name__ == '__main__':
669
    from ..dataset import DataSet
670 671
    def run():
        app = QtWidgets.QApplication(sys.argv)
672
        meas = ParticleAnalysis(DataSet("dummydata"))
673
        meas.showMaximized()
674
        return app.exec_()
675 676
    
    run()