analysisview.py 34.6 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
25 26 27 28 29 30 31 32
import sys
import random
import colorsys

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

33
from .analysiswidgets import ExpExcelDialog, AdditiveViewer
34
from .loadresults import LoadWITecResults
35
from .particleeditor import ParticleEditor
36
from .database import DataBaseWindow
37
from .datastats import DataStats
Hackmet's avatar
Hackmet committed
38
try:
39
    from .sqlexport import SQLExport
Hackmet's avatar
Hackmet committed
40 41 42
    sqlEnabled = True
except:
    sqlEnabled = False
43 44


Hackmet's avatar
Hackmet committed
45
class ParticleAnalysis(QtWidgets.QMainWindow):
46 47
    def __init__(self, dataset, parent=None):
        super(ParticleAnalysis, self).__init__(parent)
48 49 50
        self.setGeometry(100, 100, 1680, 1050)
        self.setWindowTitle('Results of polymer analysis')
        self.layout = QtWidgets.QHBoxLayout()
Hackmet's avatar
Hackmet committed
51 52 53 54
        self.widget = QtWidgets.QWidget()
        self.widget.setLayout(self.layout)
        self.setCentralWidget(self.widget)
        
55 56
        self.parent = parent
        
57 58
        self.datastats = DataStats(dataset)
        self.editor = ParticleEditor(self.datastats, self)
59 60 61
        
        self.additivePlot = None
        self.importWindow = None
62
        
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
        self.polymerCheckBoxes = []
        self.lastSelectedCheckBoxNames = []
        
        self.currentParticleIndex = 0
        self.currentSpectrumIndex = 0
        self.lastSpectrumInFocus = None
        
        self.typeHistogramCanvas = FigureCanvas(Figure())
        self.sizeHistogramCanvas = FigureCanvas(Figure())
       
        self.typeHist_ax = self.typeHistogramCanvas.figure.subplots()
        self.typeHist_ax.axis('off')
        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
82
        histNavigation.setFixedWidth(50)
83 84 85 86 87 88 89 90 91
        sizeHistLayout.addWidget(histNavigation)
        sizeHistLayout.addWidget(self.sizeHistogramCanvas)
        sizeHistGroup.setLayout(sizeHistLayout)
        
        specGroup = QtWidgets.QGroupBox()
        specLayout = QtWidgets.QHBoxLayout()
        self.specCanvas = FigureCanvas(Figure())
        self.spec_ax = self.specCanvas.figure.subplots()
        self.spec_ax.axis("off")
Hackmet's avatar
Hackmet committed
92 93
        self.ref_ax = self.spec_ax.twinx()
        self.specCanvas.figure.subplots_adjust(left=0.1, top=0.93, bottom=0.15, right=0.9)
94 95
        specNavigation = NavigationToolbar(self.specCanvas, self)
        specNavigation.setOrientation(QtCore.Qt.Vertical)
Hackmet's avatar
Hackmet committed
96
        specNavigation.setFixedWidth(50)
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
        
        specLayout.addWidget(specNavigation)
        specLayout.addWidget(self.specCanvas)
        specGroup.setLayout(specLayout)
        
        viewLayout = QtWidgets.QVBoxLayout()
        self.menuLayout = QtWidgets.QVBoxLayout()
        
        splitter1 = QtWidgets.QSplitter(QtCore.Qt.Vertical)
        splitter1.addWidget(specGroup)
        splitter1.addWidget(sizeHistGroup)
        splitter2 = QtWidgets.QSplitter(QtCore.Qt.Horizontal)
        splitter2.addWidget(splitter1)
        splitter2.addWidget(self.typeHistogramCanvas)
        splitter2.setSizes([300, 150])
       
        self.navigationGroup = QtWidgets.QGroupBox('Navigate through polymers')
        self.navigationGroup.setDisabled(True)
        navigationLayout = QtWidgets.QHBoxLayout()
        self.polymerComboBox = QtWidgets.QComboBox()
        self.polymerComboBox.currentIndexChanged.connect(self.displayNewPolymerType)
        self.polymerComboBox.setMinimumWidth(150)
        self.particleSelector = QtWidgets.QSpinBox()
        self.particleSelector.valueChanged.connect(self.selectParticle)
        self.spectrumSelector = QtWidgets.QSpinBox()
        self.spectrumSelector.valueChanged.connect(self.selectSpectrum)
        for spinbox in [self.particleSelector, self.spectrumSelector]:
            spinbox.setMinimum(1)
            spinbox.setSingleStep(1)
            spinbox.setValue(1)
        
        navigationLayout.addWidget(QtWidgets.QLabel('Select Polymer Type:'))
        navigationLayout.addWidget(self.polymerComboBox)
        navigationLayout.addStretch()
        navigationLayout.addWidget(QtWidgets.QLabel('Select Particle'))
        navigationLayout.addWidget(self.particleSelector)
        navigationLayout.addWidget(QtWidgets.QLabel('Select Spectrum'))
        navigationLayout.addWidget(self.spectrumSelector)
        navigationLayout.addStretch()
        
        self.navigationGroup.setLayout(navigationLayout)
        
Hackmet's avatar
Hackmet committed
139 140 141 142 143 144 145 146 147 148 149 150 151
        referenceGroup = QtWidgets.QGroupBox('Reference Spectra')
        referenceLayout = QtWidgets.QHBoxLayout()
        
        self.refSelector = QtWidgets.QComboBox()
        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)
        referenceGroup.setLayout(referenceLayout)
        
152 153
        topLayout = QtWidgets.QHBoxLayout()
        topLayout.addWidget(self.navigationGroup)
Hackmet's avatar
Hackmet committed
154 155
        topLayout.addWidget(referenceGroup)
        topLayout.addStretch()
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
        
        viewLayout.addLayout(topLayout)
        viewLayout.addWidget(splitter2)
        viewLayout.setStretch(1, 1)

        self.optionsGroup = QtWidgets.QGroupBox('Further Options')
        optionsLayout = QtWidgets.QFormLayout()
        
        self.hqiSpinBox = QtWidgets.QDoubleSpinBox()
        self.hqiSpinBox.setValue(75.0)
        self.hqiSpinBox.setDecimals(1)
        self.hqiSpinBox.setMinimum(0)
        optionsLayout.addRow(QtWidgets.QLabel('min HQI:'), self.hqiSpinBox)
        
        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)
        
        self.dispResultSpinBox = QtWidgets.QSpinBox()
        self.dispResultSpinBox.setValue(20)
        self.dispResultSpinBox.setMinimum(1)
        self.dispResultSpinBox.valueChanged.connect(self.updateHistogram)
        optionsLayout.addRow(QtWidgets.QLabel('Max. items in display:'), self.dispResultSpinBox)
        
        for spinbox in [self.hqiSpinBox, self.compHqiSpinBox]:
            spinbox.setMaximum(100)
            spinbox.setMaximumWidth(45)
        
        self.updateBtn = QtWidgets.QPushButton('Update Results')
        self.updateBtn.setDisabled(True)
        optionsLayout.addRow(self.updateBtn)
        
        self.optionsGroup.setLayout(optionsLayout)
        self.optionsGroup.setMinimumWidth(175)
        self.optionsGroup.setDisabled(True)
        
        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)
#        self.layout_SArea.addStretch(1)

Hackmet's avatar
Hackmet committed
216
#        self.menuLayout.addWidget(reloadGroup)
217 218 219 220 221 222
        self.menuLayout.addWidget(self.optionsGroup)
        self.menuLayout.addWidget(self.resultScrollarea)
        
        self.layout.addLayout(self.menuLayout)
        self.layout.addLayout(viewLayout)
        
Lars Bittrich's avatar
Lars Bittrich committed
223 224 225 226 227
        minHQI = self.datastats.dataset.resultParams['minHQI']
        compHQI = self.datastats.dataset.resultParams['compHQI']
        if minHQI is not None:
            self.hqiSpinBox.setValue(minHQI)
            self.compHqiSpinBox.setValue(compHQI)
228
         
Hackmet's avatar
Hackmet committed
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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        self.createActions()
        self.createMenus()
        
        self.updateData()
    
    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)
        
        self.transpAct = QtWidgets.QAction("&Transparent Overlay")
        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)
        self.overlayActGroup.triggered.connect(self.updateHistogram)
        
        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)

    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
312
            self.refSelector.addItem('')
Hackmet's avatar
Hackmet committed
313 314 315
            self.refSelector.addItems(self.dbWin.activeDatabase.spectraNames)
            self.refSelector.setDisabled(False)
            
316
    def updateData(self):
317 318 319 320 321
        spectra = self.datastats.update()
        if spectra is None:
            fname = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Spectra File', self.datastats.dataset.path, 'text file (*.txt)')[0]
            spectra = self.datastats.loadSpectra(fname)
            if spectra is None:
322 323
                QtWidgets.QMessageBox.critical(self, 'ERROR!', 'spectra file could not be opened with np.loadtxt...')
                return
Hackmet's avatar
Hackmet committed
324
        self.specCanvas.draw()
325 326 327 328
        self.loadParticleData()
        
    def loadParticleData(self):
        #check, if dataset already contains results. Otherwise load them...
329
        if not self.datastats.loadParticleData():
Hackmet's avatar
Hackmet committed
330 331 332
            self.show()
            answer = QtWidgets.QMessageBox.question(self, 'Warning', 'No (or inconsistent) spectra results found, please run import dialog.\nPress OK to import or cancel to set to empty.', QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
            if answer == QtWidgets.QMessageBox.Ok:
Hackmet's avatar
Hackmet committed
333
                self.importTrueMatchResults()
Hackmet's avatar
Hackmet committed
334
            elif answer == QtWidgets.QMessageBox.Cancel:
335
                self.datastats.invalidateSpectra()
Hackmet's avatar
Hackmet committed
336 337
                self.updateBtn.clicked.connect(self.formatResults)
                self.formatResults()
338 339 340 341
        else:
            self.updateBtn.clicked.connect(self.formatResults)
            self.formatResults()
        
Hackmet's avatar
Hackmet committed
342
    def importTrueMatchResults(self):
343 344
        self.importWindow = LoadWITecResults(self.datastats, self)
        self.importWindow.exec()
345 346 347
    
    def getAdditivePlot(self, event):
        clickedindex = int(np.round(event.xdata))
348
        polymer = self.datastats.typehistogram[clickedindex][0]        #get the polymer name, that was clicked on
349
      
350 351
        if len(self.datastats.sorted_additives[clickedindex]) > 0:            
            self.additivePlot = AdditiveViewer(polymer, self.datastats.sorted_additives[clickedindex])
352 353
            self.additivePlot.show()
    
354
    @QtCore.pyqtSlot()
355
    def formatResults(self):
356
        if self.datastats.spectraResults is not None:
Hackmet's avatar
Hackmet committed
357 358 359 360
            print('formatResults')
            self.updateBtn.setDisabled(False)
            self.optionsGroup.setDisabled(False)
            
361
            self.datastats.formatResults(self.hqiSpinBox.value(), self.compHqiSpinBox.value())
Hackmet's avatar
Hackmet committed
362
            
363
            if self.datastats.additiveResults is not None:
Hackmet's avatar
Hackmet committed
364 365 366
                self.compHqiSpinBox.setDisabled(False)
            
            self.createHistogramData()
367 368
            
    def createHistogramData(self):
369
        if not self.datastats.createHistogramData():
Hackmet's avatar
Hackmet committed
370 371
            QtWidgets.QMessageBox.critical(self, 'Error', 'Inconsistent particle data. Please restore backup!')
            return
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        
        ###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)
        self.showTotalSelector.stateChanged.connect(self.updateHistogram)
        
        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)
        #generate new checkboxes 
        self.polymerCheckBoxes = []
404 405
        uniquePolymers = self.datastats.getUniquePolymers()
        for index, polymer in enumerate(uniquePolymers):
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
            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)
            
            self.polymerCheckBoxes[index].stateChanged.connect(self.updateHistogram)
            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)
        
422
        if self.datastats.currentAdditives is not None:
423 424 425
            self.typeHistogramCanvas.setCursor(QtGui.QCursor(QtCore.Qt.WhatsThisCursor))
            self.typeHistogramCanvas.mpl_connect('button_press_event', self.getAdditivePlot)
        
Hackmet's avatar
Hackmet committed
426 427 428
        self.expExcelAct.setDisabled(False)
        if sqlEnabled:
            self.expSQLAct.setDisabled(False)
429 430 431 432
        
        self.navigationGroup.setEnabled(True)
        self.polymerComboBox.currentIndexChanged.disconnect()
        self.polymerComboBox.clear()
433
        self.polymerComboBox.addItems(uniquePolymers)
434
        self.polymerComboBox.currentIndexChanged.connect(self.displayNewPolymerType)
Hackmet's avatar
Hackmet committed
435
                
436 437 438 439 440 441
        self.polymerIndex = self.polymerComboBox.currentIndex()
        if self.lastSpectrumInFocus is not None:
            self.currentSpectrumIndex = self.lastSpectrumInFocus
            self.displayNewPolymerType(resetCurrentIndex=False)
        else:
            self.displayNewPolymerType()
Hackmet's avatar
Hackmet committed
442
            
443 444 445
        self.updateHistogram()
        self.createPolymerOverlay()
    
Hackmet's avatar
Hackmet committed
446
    def exportToExcel(self):
447
        expWin = ExpExcelDialog(self.datastats, self)
448
        expWin.exec()
Hackmet's avatar
Hackmet committed
449 450
            
    def exportToSQL(self):
451
        sqlexp = SQLExport(self.datastats, self)
452 453
        sqlexp.exec()
        
454
    
Hackmet's avatar
Hackmet committed
455 456
    def updateSpecPlot(self, centerOn=True, highlightContour=True):
        #draw Sample Spectrum
457
        specIndex = self.currentSpectrumIndex
458
        spectra = self.datastats.spectra
459
        particlestats = self.datastats.getParticleStats()
460 461
        self.spec_ax.axis("on")
        self.spec_ax.clear()
462
        self.spec_ax.plot(spectra[:, 0], spectra[:, specIndex+1])
463 464 465
        self.spec_ax.tick_params(axis='both', which='both', labelsize=15)
        self.spec_ax.set_xlabel('Wavenumber (cm-1)', fontsize = 15)
        self.spec_ax.set_ylabel('Counts', fontsize = 15)
466
        self.spec_ax.set_title('ScanPoint Number {}, Size = {} µm'.format(specIndex+1, 
467
                               np.round(particlestats[self.currentParticleIndex][2], 1)))
468 469
        self.spec_ax.set_xbound(100, (3400 if spectra[-1, 0] > 3400 else spectra[-1, 0]))
        wavenumber_diff = list(spectra[:, 0]-100)
Hackmet's avatar
Hackmet committed
470
        y_start = wavenumber_diff.index(min(wavenumber_diff))
471 472
        y_min = min(spectra[y_start:, specIndex+1])
        y_max = max(spectra[y_start:, specIndex+1])
Hackmet's avatar
Hackmet committed
473 474 475 476 477 478 479 480 481 482 483
        self.spec_ax.set_ybound(0.9*y_min, 1.1*y_max)
        
        #draw Reference
        self.ref_ax.clear()
        if self.refSelector.isEnabled() and self.refSelector.currentText() != '':
            self.ref_ax.tick_params(axis='both', which='both', labelsize=15)
            refID = self.dbWin.activeDatabase.spectraNames.index(self.refSelector.currentText())
            ref = self.dbWin.activeDatabase.spectra[refID]
            self.ref_ax.plot(ref[:, 0], ref[:, 1], color = 'r')
            self.ref_ax.set_ylabel('Ref. Intensity', fontsize = 15, color = 'r')
            self.ref_ax.tick_params('y', colors = 'r')
484
            self.ref_ax.set_xbound(100, (3400 if spectra[-1, 0] > 3400 else spectra[-1, 0]))
Hackmet's avatar
Hackmet committed
485 486 487 488 489 490 491
#            wavenumber_diff = list(ref[:, 0]-100)
#            y_start = wavenumber_diff.index(min(wavenumber_diff))
#            y_min = min(ref[y_start:, specIndex+1])
#            y_max = max(ref[y_start:, specIndex+1])
            
            
        
492 493 494 495
        self.spec_ax.figure.canvas.draw()
        self.parent.centerOnRamanIndex(specIndex, centerOn=centerOn, highlightContour=highlightContour)
        self.parent.highLightRamanIndex(specIndex)
        self.lastSpectrumInFocus = specIndex
496 497 498 499 500 501
        
    def selectContour(self, index, centerOn=True):
        uniquePolymers = self.datastats.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
502 503
            self.currentParticleIndex = index
            self.currentSpectrumIndex = specIndex
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
            
            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()
            self.polymerComboBox.currentIndexChanged.disconnect()
            
            #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)
            self.polymerComboBox.setCurrentIndex(self.polymerIndex)
           
            #reconnect all widgets:
            self.particleSelector.valueChanged.connect(self.selectParticle)
            self.spectrumSelector.valueChanged.connect(self.selectSpectrum)
            self.polymerComboBox.currentIndexChanged.connect(self.displayNewPolymerType)
            
            self.updateSpecPlot(centerOn=centerOn)
538 539 540
    
    def displayNewPolymerType(self, resetCurrentIndex=True):
        self.polymerIndex = self.polymerComboBox.currentIndex()
541
        self.particleSelector.setMaximum(len(self.datastats.indices[self.polymerIndex]))
542 543 544
        if resetCurrentIndex:
            self.particleSelector.setValue(1)
            self.spectrumSelector.setValue(1)
545 546 547
            self.spectrumSelector.setMaximum(len(self.datastats.particles2spectra[self.currentParticleIndex]))
            self.currentParticleIndex = self.datastats.indices[self.polymerIndex][self.particleSelector.value()-1]
            self.currentSpectrumIndex = self.datastats.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
548
            self.updateSpecPlot(centerOn=True)
549
        else:    
550 551
            self.currentParticleIndex = self.datastats.indices[self.polymerIndex][self.particleSelector.value()-1]
            self.currentSpectrumIndex = self.datastats.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
552
            self.updateSpecPlot(centerOn=False)
553 554
    
    def selectParticle(self, resetSpectrumCount=True):
555 556 557
        if self.datastats.particles2spectra is not None:
            self.currentParticleIndex = self.datastats.indices[self.polymerIndex][self.particleSelector.value()-1]
            self.spectrumSelector.setMaximum(len(self.datastats.particles2spectra[self.currentParticleIndex]))
558 559
            if resetSpectrumCount:
                self.spectrumSelector.setValue(1)
560
            self.currentSpectrumIndex = self.datastats.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
561
            self.updateSpecPlot()
562 563 564 565
        else:
            print('no spectrum assignment found...')
    
    def selectSpectrum(self):
566 567
        if self.datastats.particles2spectra is not None:
            self.currentSpectrumIndex = self.datastats.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
568
            self.updateSpecPlot()
569 570 571 572 573 574 575 576 577 578
    
    def updateHistogram(self):
        self.sizeHist_ax.clear()
        self.typeHist_ax.clear()
        
        self.typeHist_ax.axis('on')
        self.sizeHist_ax.axis('on')
  
        #draw the general histogram
        colorList = []
Hackmet's avatar
Hackmet committed
579
        if self.selOverlayAct.isChecked():
580 581 582
            abundancyList = []
            for index, checkbox in enumerate(self.polymerCheckBoxes):
                if checkbox.isChecked():
583 584
                    abundancyList.append(self.datastats.typehistogram[index][1])
                    curColor = self.getColorFromName(self.datastats.typehistogram[index][0], base255 = False)
585 586 587
                    colorList.append(curColor)

        else:
588 589
            abundancyList = [i[1] for i in self.datastats.typehistogram]
            for polymer in self.datastats.typehistogram:
590 591 592 593 594 595 596 597 598 599
                curColor = self.getColorFromName(polymer[0], base255 = False)
                colorList.append(curColor)                    
                
        self.typeHist_ax.barh(range(len(abundancyList)), abundancyList, color=colorList)
        itemsInPlot = (len(abundancyList) if len(abundancyList) < self.dispResultSpinBox.value() else self.dispResultSpinBox.value())
        self.typeHist_ax.set_ylim([itemsInPlot, -1])    #plot in inverse order (have index 0 (highest abundancy) at top)
        
        ###add text labels
        self.histPlotTextLabels = []
        y_label_position = 0
600
        for index, i in enumerate(self.datastats.typehistogram):
Hackmet's avatar
Hackmet committed
601
            if not self.selOverlayAct.isChecked() or self.polymerCheckBoxes[index].isChecked():
602
                if self.datastats.sorted_additives is None:
603 604
                    numads = ''
                else:
605
                    numads = len(np.unique(self.datastats.sorted_additives[index]))    
606 607 608 609 610
                    if numads == 0: 
                        numads = ''
                    else:
                        numads = '(' + str(numads) + ')'
                numpolymers = i[1]
611
                label = ('{} x ' + self.datastats.typehistogram[index][0] + ' {}').format(numpolymers, numads) 
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
                x_label_position = self.typeHist_ax.get_xlim()[1]*0.05
                self.histPlotTextLabels.append(self.typeHist_ax.text(x_label_position, y_label_position, label, fontsize = 15, rotation = 0, verticalalignment = 'bottom'))
                y_label_position += 1
            
        for label in self.histPlotTextLabels:
            pos = label.get_position()
            curLimits = self.typeHist_ax.get_ylim()
            if curLimits[1] < pos[1] < curLimits[0]:
                label.set_alpha(1)
            else:
                label.set_alpha(0)
                
        self.typeHist_ax.set_title('Polymer Type Distribution', fontsize = 15)
        self.typeHist_ax.tick_params(axis='y', which='both', left=False, labelleft=False)        
        self.typeHist_ax.tick_params(axis='both', which='both', labelsize=15)
        self.typeHist_ax.set_ylabel('Polymer Type', fontsize = 15)
        self.typeHist_ax.set_xlabel('Number', fontsize = 15)
        
630
        if len(self.datastats.typehistogram) > self.dispResultSpinBox.value():
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
            
            def wheelScroll(event):
                step = -0.05*event.step*self.dispResultSpinBox.value()
                ymin, ymax = self.typeHist_ax.get_ylim()
                if ymin > ymax:
                    ymin, ymax = ymax, ymin
                self.typeHist_ax.set_ylim([ymax+step, ymin+step])
                
                for label in self.histPlotTextLabels:
                    pos = label.get_position()
                    if ymin+step < pos[1] < ymax+step:
                        label.set_alpha(1)
                    else:
                        label.set_alpha(0)                
                self.typeHist_ax.figure.canvas.draw()
            
            self.typeHistogramCanvas.mpl_connect('scroll_event', wheelScroll)
        
        self.typeHist_ax.figure.canvas.draw()
        
        #general size histogram
        self.bins = np.logspace(0.1, 3, 20)
653
        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)
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        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
        selected = []
        for i in self.polymerCheckBoxes:
            if i.isChecked() == True:
                selected.append(i.text())
        
        for i in selected:
676 677
            sizes = [self.sizes[index] for index in range(len(self.sizes)) 
                        if self.datastats.currentPolymers[index] == i]
678 679 680 681 682 683 684 685 686 687 688 689 690 691
            sizehist = np.histogram(sizes, self.bins)
            self.sizeHist_ax.semilogx(self.totalhistx, sizehist[0], label = i, color = self.getColorFromName(i, base255 = False))    
        
        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()]
        
     
    def darkenBackground(self):
Hackmet's avatar
Hackmet committed
692
        self.parent.darkenPixmap = self.darkenAct.isChecked()
693
        
Hackmet's avatar
Hackmet committed
694
        if self.darkenAct.isChecked():
695 696 697 698 699 700 701
            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):
702
        text, ok = QtWidgets.QInputDialog.getText(self, 'Color Seed', 'Enter New Seed here', text=self.datastats.colorSeed)
703
        if ok:
704 705
            self.datastats.colorSeed = text
            self.datastats.dataset.colorSeed = text
706 707 708 709
            self.updateHistogram()
            self.createPolymerOverlay()

    def getColorFromName(self, name, base255=True):
710
        random.seed(self.datastats.colorSeed + name)
711
        hue = random.random()
712
        random.seed((self.datastats.colorSeed + name)*2)
713
        saturation = random.random()/4 + 0.75      #i.e., between 0.75 and 1
714
        random.seed((self.datastats.colorSeed + name)*3)
715 716 717 718 719 720 721 722 723 724
        value = random.random()/5 + 0.8     #i.e., between 0.8 and 1
        color = colorsys.hsv_to_rgb(hue, saturation, value)
        if base255:
            color = list(color)
            for i in range(3):
                color[i] = np.round(color[i]*255)
            color = tuple(color)
        return color
    
    def createPolymerOverlay(self):  
725
        uniquePolymers = self.datastats.getUniquePolymers()
726 727
        if not self.noOverlayAct.isChecked() and self.datastats.indices is not None:
            if len(self.datastats.indices) > 0:
728
                
Hackmet's avatar
Hackmet committed
729
                alpha = (128 if self.transpAct.isChecked() else 255)
730
                #get colors for each polymer type
731
                colorList = [QtGui.QColor(255, 255, 255, alpha=50)]*len(self.datastats.particleResults)
732 733
                legendItems = []
                    
734
                for index, indexList in enumerate(self.datastats.indices):
Hackmet's avatar
Hackmet committed
735
                    if self.fullOverlayAct.isChecked() or (self.selOverlayAct.isChecked() and self.polymerCheckBoxes[index].isChecked()):
736
                        color = self.getColorFromName(uniquePolymers[index], base255=True)
737
                        color = QtGui.QColor(color[0], color[1], color[2], alpha=alpha)
738
                        legendItems.append((uniquePolymers[index], color))
739 740 741 742 743 744
                        for i in indexList:
                            colorList[i] = color
            
            self.parent.contouritem.colorList = colorList
            self.parent.contouritem.update()
            
745
            self.parent.imparent.legend.setTextColorItems(legendItems)
746 747 748 749 750
            self.parent.imparent.legend.show()
            
        else:
            self.parent.contouritem.colorList = []
            self.parent.contouritem.update()
751
            self.parent.imparent.legend.setTextColorItems([])
752 753 754
            self.parent.imparent.legend.hide()
            
    def show_hide_labels(self):
Hackmet's avatar
Hackmet committed
755
        hidden = self.hideLabelAct.isChecked()
756 757 758
        for scanIndicator in self.parent.ramanscanitems:
            scanIndicator.hidden = hidden
            scanIndicator.update()
Hackmet's avatar
Hackmet committed
759

760 761
    
    def closeEvent(self, event):
762
        for window in [self.additivePlot, self.importWindow, self.dbWin]:
763 764
            try: window.close()
            except: pass
Hackmet's avatar
Hackmet committed
765
        self.parent.imparent.particelAnalysisAct.setChecked(False)
766 767 768 769
        event.accept()


if __name__ == '__main__':
770
    from ..dataset import DataSet
771 772
    def run():
        app = QtWidgets.QApplication(sys.argv)
773
        meas = ParticleAnalysis(DataSet("dummydata"))
774
        meas.showMaximized()
775
        return app.exec_()
776 777
    
    run()