analysisview.py 49.7 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
#!/usr/bin/env python3
# -*- 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/>.
"""

import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import operator
import os
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

import pandas as pd
from analysis.loadresults import LoadWITecResults
from analysis.editParticles import ParticleEditor
Hackmet's avatar
Hackmet committed
38
from analysis.database import DataBaseWindow
Hackmet's avatar
Hackmet committed
39 40 41 42 43
try:
    from analysis.sqlexport import SQLExport
    sqlEnabled = True
except:
    sqlEnabled = False
44 45


Hackmet's avatar
Hackmet committed
46
class ParticleAnalysis(QtWidgets.QMainWindow):
47 48 49 50 51
    def __init__(self, parent):
        super(ParticleAnalysis, self).__init__()
        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 57 58 59 60
        self.parent = parent
        if self.parent is not None:
            self.config = self.parent.dataset.resultParams
        
        self.editor = ParticleEditor(self)
Hackmet's avatar
Hackmet committed
61
        self.expWin = None
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
        
        self.spectraResults = None                  #entire List of all spectra assignments
        self.additiveResults = None                 #entire List of all additives
        self.particlestats = None
        self.particleResults = None                 #final assignment for each particle
        
        self.currentPolymers = None                 #list of polymers after setting entries with low hqi to unknown
        self.currentAdditives = None                #same thing for the additives
        self.uniquePolymers = None                  #list of present polymer types
        self.spectra = None                         #acquired spectra
        self.indices = None                         #assignment of what spectra-indices belong to what substance
        self.expWindow = None
        self.additivePlot = None
        self.importWindow = None
        self.directory = None
        self.particles2spectra = None
        self.manualPolymers = {}
        self.manualAdditives = {}
        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
99
        histNavigation.setFixedWidth(50)
100 101 102 103 104 105 106 107 108
        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
109 110
        self.ref_ax = self.spec_ax.twinx()
        self.specCanvas.figure.subplots_adjust(left=0.1, top=0.93, bottom=0.15, right=0.9)
111 112
        specNavigation = NavigationToolbar(self.specCanvas, self)
        specNavigation.setOrientation(QtCore.Qt.Vertical)
Hackmet's avatar
Hackmet committed
113
        specNavigation.setFixedWidth(50)
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
        
        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
156 157 158 159 160 161 162 163 164 165 166 167 168
        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)
        
169 170
        topLayout = QtWidgets.QHBoxLayout()
        topLayout.addWidget(self.navigationGroup)
Hackmet's avatar
Hackmet committed
171 172
        topLayout.addWidget(referenceGroup)
        topLayout.addStretch()
173 174 175 176 177
        
        viewLayout.addLayout(topLayout)
        viewLayout.addWidget(splitter2)
        viewLayout.setStretch(1, 1)
        
Hackmet's avatar
Hackmet committed
178 179 180 181 182 183 184 185 186 187 188
#        reloadGroup = QtWidgets.QGroupBox('Reload Results from:')
#        reloadLayout = QtWidgets.QVBoxLayout()
#        self.reloadWITec = QtWidgets.QRadioButton('WITec True Match')
#        self.reloadWITec.setChecked(True)
#        self.reloadTxt = QtWidgets.QRadioButton('Ordered text file')
#        reloadBtn = QtWidgets.QPushButton('reload Results')
#        reloadBtn.clicked.connect(self.importResults)
#        reloadLayout.addWidget(self.reloadWITec)
#        reloadLayout.addWidget(self.reloadTxt)
#        reloadLayout.addWidget(reloadBtn)
#        reloadGroup.setLayout(reloadLayout)
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

        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
245
#        self.menuLayout.addWidget(reloadGroup)
246 247 248 249 250 251 252 253 254 255 256 257
        self.menuLayout.addWidget(self.optionsGroup)
        self.menuLayout.addWidget(self.resultScrollarea)
        
        self.layout.addLayout(self.menuLayout)
        self.layout.addLayout(viewLayout)
        
#        update config, if present:
        if self.parent is not None:
            if self.config['minHQI'] is not None:
                self.hqiSpinBox.setValue(self.config['minHQI'])
                self.compHqiSpinBox.setValue(self.config['compHQI'])
         
Hackmet's avatar
Hackmet committed
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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
        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:
            self.refSelector.addItems(self.dbWin.activeDatabase.spectraNames)
            self.refSelector.setDisabled(False)
                
    
345
    def loadSpectra(self, fname):
Hackmet's avatar
Hackmet committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        import time
        t0 = time.time()
        specfilename = self.parent.dataset.fname.split('.pkl')[0] + '_spectra.npy'
        if os.path.exists(specfilename):
            return np.load(specfilename)
        else:
            try:
                specs = np.loadtxt(fname)
                #if spectra are already in correct format (WITec, first column: wavenumbers, other columns, intensities), 
                #we take them, otherwise we have to convert from Renishaw export format...
                if not len(np.unique(specs[:, 0])) == len(specs[:, 0]): #--> only unique numbers -> this is the wavenumber column, we have the witec format
                    #Renishaw Convert  
                    #columns 0 and 1 are x and y coordinates. We dont need them...
                    startWavenumber = specs[0, 2]
                    startIndices = np.where(specs[:, 2] == startWavenumber)[0]
                    
                    spectra = np.zeros((startIndices[1], len(startIndices)+1))   #create array with shape (numWavenumbers, numSpectra+1) (first column holds wavenumbers)
                    spectra[:, 0] = specs[startIndices[0]:startIndices[1], 2]
                    for i in range(len(startIndices)-1):
                        spectra[:, i+1] = specs[startIndices[i]:startIndices[i+1], 3]
                    #aaand the last spectrum:
                    spectra[:, -1] = specs[startIndices[-1]:, 3]
                    specs = np.flip(spectra, 0)    #Renishaw goes from highest to lowest wavenumber, out of whatever reason...
                    
                #write spectra to binary file, that makes reloading them in future significantly faster
                np.save(specfilename, specs)
                print('loading specs:', time.time()-t0)
Hackmet's avatar
Hackmet committed
373 374
                return specs
                
Hackmet's avatar
Hackmet committed
375 376 377 378
            except:
                raise
                return None
            
379 380 381 382 383
    def updateData(self):
        self.spectraResults = self.parent.dataset.results['polymers']
        self.additiveResults = self.parent.dataset.results['additives']
        self.hqis = self.parent.dataset.results['hqis']
        self.addhqis = self.parent.dataset.results['additive_hqis']
Hackmet's avatar
Hackmet committed
384
                
385 386 387 388 389
        self.colorSeed = self.parent.dataset.colorSeed
        if type(self.colorSeed) != str:
            self.colorSeed = 'default'
        
        #load Spectra
Hackmet's avatar
Hackmet committed
390 391 392 393 394
        if self.parent.dataset.spectraPath is None:
            fname = os.path.join(self.parent.dataset.path, self.parent.dataset.name + '_000_Spec.Data 1.txt')
        else:
            fname = self.parent.dataset.spectraPath
        self.spectra = self.loadSpectra(fname)
395 396 397 398 399 400
        if self.spectra is None:
            fname = QtWidgets.QFileDialog.getOpenFileName(self, 'Select Spectra File', self.parent.dataset.path, 'text file (*.txt)')[0]
            self.spectra = self.loadSpectra(fname)
            if self.spectra is None:
                QtWidgets.QMessageBox.critical(self, 'ERROR!', 'spectra file could not be opened with np.loadtxt...')
                return
Hackmet's avatar
Hackmet committed
401
        self.parent.dataset.spectraPath = fname
Hackmet's avatar
Hackmet committed
402
#        self.spec_ax.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
Hackmet's avatar
Hackmet committed
403 404 405
        self.specCanvas.draw()
        
        ####fake data!!!
Hackmet's avatar
Hackmet committed
406 407 408
#        if self.spectraResults is None:
#            self.spectraResults = ['empty']*(self.spectra.shape[1]-1)
#            self.hqis = [100]*(self.spectra.shape[1]-1)
Hackmet's avatar
Hackmet committed
409
        
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        self.loadParticleData()
        
    def loadParticleData(self):
        self.particlestats = np.array(self.parent.dataset.particlestats)
        pixelscale = (self.parent.dataset.pixelscale_df if self.parent.dataset.imagescanMode == 'df' else self.parent.dataset.pixelscale_bf)
        #convert to mikrometer scale
        for index in range(len(self.particlestats)):
            for subindex in range(5):
                self.particlestats[index][subindex] = self.particlestats[index][subindex] * pixelscale    #multiply by pixelscale
                if subindex == 4:
                    self.particlestats[index][subindex] = self.particlestats[index][subindex] * pixelscale  #again for the area...
        
        self.particles2spectra = self.parent.dataset.particles2spectra
        
        sortindices = self.parent.dataset.ramanscansortindex
        if self.particles2spectra is None:
            print('creating default particles2spectra list')
            #no assignment found, so we assume one measurement per particle and use ramanscansortindex for assignment
            self.particles2spectra = [[int(np.where(sortindices == i)[0])] for i in range(len(sortindices))]
        
        #check, if dataset already contains results. Otherwise load them...
        if self.spectraResults is None or (len(self.spectraResults) != len(sortindices)):
Hackmet's avatar
Hackmet committed
432 433 434 435 436 437 438 439 440 441
            self.show()
#            QtWidgets.QMessageBox.about(self, 'Info', 'No (or inconsistent) spectra results found, please run import dialog.')
            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:
                self.importResults()
            elif answer == QtWidgets.QMessageBox.Cancel:
                self.spectraResults = ['empty']*(self.spectra.shape[1]-1)
                self.hqis = [100]*(self.spectra.shape[1]-1)
                self.updateBtn.clicked.connect(self.formatResults)
                self.formatResults()
442 443 444 445
        else:
            self.updateBtn.clicked.connect(self.formatResults)
            self.formatResults()
        
Hackmet's avatar
Hackmet committed
446 447 448
    def importTrueMatchResults(self):
        self.importWindow = LoadWITecResults(self)
        self.importWindow.show()
449 450 451 452 453 454 455 456 457 458
    
    def getAdditivePlot(self, event):
        clickedindex = int(np.round(event.xdata))
        polymer = self.typehistogram[clickedindex][0]        #get the polymer name, that was clicked on
      
        if len(self.sorted_additives[clickedindex]) > 0:            
            self.additivePlot = AdditiveViewer(polymer, self.sorted_additives[clickedindex])
            self.additivePlot.show()
    
    def formatResults(self):
Hackmet's avatar
Hackmet committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        if self.spectraResults is not None:
            print('formatResults')
            self.updateBtn.setDisabled(False)
            self.optionsGroup.setDisabled(False)
            del self.currentPolymers, self.currentAdditives
            
            #convert to arrays (makes indexing easier...)
            self.currentPolymers, self.hqis = np.array(self.spectraResults), np.array(self.hqis)
            
            if self.additiveResults is not None:
                self.currentAdditives, self.addhqis = np.array(self.additiveResults), np.array(self.addhqis)
                self.compHqiSpinBox.setDisabled(False)
            else:
                self.currentAdditives = None
            
            #set poor HQI results to unknown
            self.currentPolymers[self.hqis < self.hqiSpinBox.value()] = 'unknown'
            
            if self.currentAdditives is not None:
                self.currentAdditives[self.addhqis < self.compHqiSpinBox.value()] = 'unknown'
            
            self.createHistogramData()
481 482 483 484 485 486
            
    def createHistogramData(self):
        self.uniquePolymers = np.unique(self.currentPolymers)
        self.particleResults = [None]*len(self.particlestats)
        self.typehistogram = {i: 0 for i in self.uniquePolymers}
        
Hackmet's avatar
Hackmet committed
487 488 489
        if len(self.particles2spectra) != len(self.particlestats):
            QtWidgets.QMessageBox.critical(self, 'Error', 'Inconsistent particle data. Please restore backup!')
            return
490 491 492 493 494 495 496 497 498 499 500 501 502 503 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 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
        
        for particleID, specList in enumerate(self.particles2spectra):
            assignment = self.currentPolymers[specList[0]]   #we take the first result as particle result. Hence, all spectra per particle have to have the same result
            self.particleResults[particleID] = assignment
            self.typehistogram[assignment] += 1
            
        self.particleResults = np.array(self.particleResults)
        
        ##sort typehistogram, it will be converted into a list!!
        self.typehistogram = sorted(self.typehistogram.items(), key = operator.itemgetter(1), reverse = True)
        
        self.uniquePolymers = [i[0] for i in self.typehistogram]
        
        self.indices = []      #what particles belong to which polymer type?
        for polymer in self.uniquePolymers:
            self.indices.append(list(np.where(self.particleResults == polymer)[0]))
            

        ###generate additive array for each type in typehistogram:
        if self.currentAdditives is None:
            self.sorted_additives = None
        else:
            self.sorted_additives = []
            
            for polymer in self.typehistogram:  #get additives of each polymer type
                self.sorted_additives.append(self.currentAdditives[np.where(self.currentPolymers == polymer[0])])
            for i in range(len(self.sorted_additives)):         #sort out 'none' entries
                nonentries = np.where(self.sorted_additives[i] == 'none')
                self.sorted_additives[i] = np.delete(self.sorted_additives[i], nonentries)
        
        ###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 = []
        for index, polymer in enumerate(self.uniquePolymers):
            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)
        
        if self.currentAdditives is not None:
            self.typeHistogramCanvas.setCursor(QtGui.QCursor(QtCore.Qt.WhatsThisCursor))
            self.typeHistogramCanvas.mpl_connect('button_press_event', self.getAdditivePlot)
        
Hackmet's avatar
Hackmet committed
572 573 574
        self.expExcelAct.setDisabled(False)
        if sqlEnabled:
            self.expSQLAct.setDisabled(False)
575 576 577 578 579 580
        
        self.navigationGroup.setEnabled(True)
        self.polymerComboBox.currentIndexChanged.disconnect()
        self.polymerComboBox.clear()
        self.polymerComboBox.addItems(self.uniquePolymers)
        self.polymerComboBox.currentIndexChanged.connect(self.displayNewPolymerType)
Hackmet's avatar
Hackmet committed
581
                
582 583 584 585 586 587
        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
588
            
589 590 591
        self.updateHistogram()
        self.createPolymerOverlay()
    
Hackmet's avatar
Hackmet committed
592 593 594 595 596 597 598 599 600 601 602 603 604
    def exportToExcel(self):
        if self.expWin is not None:
            self.expWin.close()
            self.expWin.destroy()
        self.expWin = ExpExcelDialog(self)
        self.expWin.show()
            
    def exportToSQL(self):
        if self.expWin is not None:
            self.expWin.close()
            self.expWin.destroy()
        self.expWin = SQLExport(self)
        self.expWin.show()
605
    
Hackmet's avatar
Hackmet committed
606 607
    def updateSpecPlot(self, centerOn=True, highlightContour=True):
        #draw Sample Spectrum
608 609 610 611 612 613 614 615
        specIndex = self.currentSpectrumIndex
        self.spec_ax.axis("on")
        self.spec_ax.clear()
        self.spec_ax.plot(self.spectra[:, 0], self.spectra[:, specIndex+1])
        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)
        self.spec_ax.set_title('ScanPoint Number {}, Size = {} µm'.format(specIndex+1, np.round(self.particlestats[self.currentParticleIndex][2], 1)))
Hackmet's avatar
Hackmet committed
616
        self.spec_ax.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
Hackmet's avatar
Hackmet committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        wavenumber_diff = list(self.spectra[:, 0]-100)
        y_start = wavenumber_diff.index(min(wavenumber_diff))
        y_min = min(self.spectra[y_start:, specIndex+1])
        y_max = max(self.spectra[y_start:, specIndex+1])
        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')
            self.ref_ax.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
#            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])
            
            
        
640 641 642 643 644 645 646 647 648 649 650 651 652 653
        self.spec_ax.figure.canvas.draw()
        self.parent.centerOnRamanIndex(specIndex, centerOn=centerOn, highlightContour=highlightContour)
        self.parent.highLightRamanIndex(specIndex)
        self.lastSpectrumInFocus = specIndex
    
    def displayNewPolymerType(self, resetCurrentIndex=True):
        self.polymerIndex = self.polymerComboBox.currentIndex()
        self.particleSelector.setMaximum(len(self.indices[self.polymerIndex]))
        if resetCurrentIndex:
            self.particleSelector.setValue(1)
            self.spectrumSelector.setValue(1)
            self.spectrumSelector.setMaximum(len(self.particles2spectra[self.currentParticleIndex]))
            self.currentParticleIndex = self.indices[self.polymerIndex][self.particleSelector.value()-1]
            self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
654
            self.updateSpecPlot(centerOn=True)
655 656 657
        else:    
            self.currentParticleIndex = self.indices[self.polymerIndex][self.particleSelector.value()-1]
            self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
658
            self.updateSpecPlot(centerOn=False)
659 660 661 662 663 664 665 666
    
    def selectParticle(self, resetSpectrumCount=True):
        if self.particles2spectra is not None:
            self.currentParticleIndex = self.indices[self.polymerIndex][self.particleSelector.value()-1]
            self.spectrumSelector.setMaximum(len(self.particles2spectra[self.currentParticleIndex]))
            if resetSpectrumCount:
                self.spectrumSelector.setValue(1)
            self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
667
            self.updateSpecPlot()
668 669 670 671 672 673
        else:
            print('no spectrum assignment found...')
    
    def selectSpectrum(self):
        if self.particles2spectra is not None:
            self.currentSpectrumIndex = self.particles2spectra[self.currentParticleIndex][self.spectrumSelector.value()-1]
Hackmet's avatar
Hackmet committed
674
            self.updateSpecPlot()
675 676 677 678 679 680 681 682 683 684
    
    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
685
        if self.selOverlayAct.isChecked():
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
            abundancyList = []
            for index, checkbox in enumerate(self.polymerCheckBoxes):
                if checkbox.isChecked():
                    abundancyList.append(self.typehistogram[index][1])
                    curColor = self.getColorFromName(self.typehistogram[index][0], base255 = False)
                    colorList.append(curColor)

        else:
            abundancyList = [i[1] for i in self.typehistogram]
            for polymer in self.typehistogram:
                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
        for index, i in enumerate(self.typehistogram):
Hackmet's avatar
Hackmet committed
707
            if not self.selOverlayAct.isChecked() or self.polymerCheckBoxes[index].isChecked():
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
                if self.sorted_additives is None:
                    numads = ''
                else:
                    numads = len(np.unique(self.sorted_additives[index]))    
                    if numads == 0: 
                        numads = ''
                    else:
                        numads = '(' + str(numads) + ')'
                numpolymers = i[1]
                label = ('{} x ' + self.typehistogram[index][0] + ' {}').format(numpolymers, numads) 
                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)
        
        if len(self.typehistogram) > self.dispResultSpinBox.value():
            
            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)
        self.sizes = [i[0] if np.isnan(i[2]) else i[2] for i in self.particlestats]      #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
        selected = []
        for i in self.polymerCheckBoxes:
            if i.isChecked() == True:
                selected.append(i.text())
        
        for i in selected:
            sizes = [self.sizes[index] for index in range(len(self.sizes)) if self.currentPolymers[index] == i]
            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
797
        self.parent.darkenPixmap = self.darkenAct.isChecked()
798
        
Hackmet's avatar
Hackmet committed
799
        if self.darkenAct.isChecked():
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
            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):
        text, ok = QtWidgets.QInputDialog.getText(self, 'Color Seed', 'Enter New Seed here', text=self.colorSeed)
        if ok:
            self.colorSeed = text
            self.parent.dataset.colorSeed = text
            self.updateHistogram()
            self.createPolymerOverlay()

    def getColorFromName(self, name, base255=True):
        random.seed(self.colorSeed + name)
        hue = random.random()
        random.seed((self.colorSeed + name)*2)
        saturation = random.random()/4 + 0.75      #i.e., between 0.75 and 1
        random.seed((self.colorSeed + name)*3)
        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):  
Hackmet's avatar
Hackmet committed
830
        if not self.noOverlayAct.isChecked() and self.indices is not None:
831 832
            if len(self.indices) > 0:
                
Hackmet's avatar
Hackmet committed
833
                alpha = (128 if self.transpAct.isChecked() else 255)
834 835 836 837 838
                #get colors for each polymer type
                colorList = [QtGui.QColor(255, 255, 255, alpha=50)]*len(self.particleResults)
                legendItems = []
                    
                for index, indexList in enumerate(self.indices):
Hackmet's avatar
Hackmet committed
839
                    if self.fullOverlayAct.isChecked() or (self.selOverlayAct.isChecked() and self.polymerCheckBoxes[index].isChecked()):
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
                        color = self.getColorFromName(self.uniquePolymers[index], base255=True)
                        color = QtGui.QColor(color[0], color[1], color[2], alpha=alpha)
                        legendItems.append((self.uniquePolymers[index], color))
                        for i in indexList:
                            colorList[i] = color
            
            self.parent.contouritem.colorList = colorList
            self.parent.contouritem.update()
            
            self.parent.imparent.legend.items = legendItems
            self.parent.imparent.legend.update()
            self.parent.imparent.legend.show()
            
        else:
            self.parent.contouritem.colorList = []
            self.parent.contouritem.update()
            self.parent.imparent.legend.items = []
            self.parent.imparent.legend.update()
            self.parent.imparent.legend.hide()
            
    def show_hide_labels(self):
Hackmet's avatar
Hackmet committed
861
        hidden = self.hideLabelAct.isChecked()
862 863 864 865 866 867 868 869 870 871 872 873 874 875
        for scanIndicator in self.parent.ramanscanitems:
            scanIndicator.hidden = hidden
            scanIndicator.update()
    
    def saveAnalysisResults(self):
        self.parent.dataset.results = {'polymers': self.spectraResults,
                                'hqis': self.hqis,
                                'additives': self.additiveResults,
                                'additive_hqis': self.addhqis}
        
        self.parent.dataset.resultParams = {'minHQI': self.hqiSpinBox.value(),
                                     'compHQI': self.compHqiSpinBox.value()}
        self.parent.dataset.save()
        print('saved dataset')
Hackmet's avatar
Hackmet committed
876

877 878
    
    def closeEvent(self, event):
Hackmet's avatar
Hackmet committed
879
        for window in [self.expWindow, self.additivePlot, self.importWindow, self.dbWin]:
880 881 882 883 884 885
            try: window.close()
            except: pass
        self.saveAnalysisResults()
        event.accept()


Hackmet's avatar
Hackmet committed
886
class ExpExcelDialog(QtWidgets.QWidget):
887
    def __init__(self, parent):
Hackmet's avatar
Hackmet committed
888
        super(ExpExcelDialog, self).__init__()
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
        self.setWindowTitle('Export Options')
        self.setGeometry(200,200, 300, 300)
        
        self.parent = parent
        self.particles = self.parent.particlestats
        self.polymers = self.parent.particleResults
        self.additives = self.parent.currentAdditives
        self.hqis = self.parent.hqis
        
        self.layout = QtWidgets.QHBoxLayout()
        self.setLayout(self.layout)

        excelvbox = QtWidgets.QVBoxLayout()
        excelvbox.addWidget(QtWidgets.QLabel('Select Parameters for Export'))
        excelgroup = QtWidgets.QGroupBox("Export to Excel", self)
        
        self.exportOptions = ['Polymer Type (mandatory)', 'Additives', 'Long Size (µm)', 'Short Size (µm)', 'Area (µm²)', 'HQI', 'Size Classes']
        self.checkBoxes = []
        self.sizeClasses = [5, 10, 20, 50, 100, 1e6]
        self.directory = self.parent.parent.dataset.path
        
        for index, option in enumerate(self.exportOptions):
            self.checkBoxes.append(QtWidgets.QCheckBox(self))
            self.checkBoxes[-1].setText(option)
            self.checkBoxes[-1].setChecked(True)
            
            if option == 'Polymer Type (mandatory)':
                self.checkBoxes[-1].setEnabled(False)           #is mandatory!!!
            
            if option == 'Additives':
                if self.additives is None:
                    self.checkBoxes[-1].setEnabled(False)
                    self.checkBoxes[-1].setChecked(False)
                    
            excelvbox.addWidget(self.checkBoxes[-1])
        
        self.xlsFileName = QtWidgets.QLineEdit()
        self.xlsFileName.setText('{}_Particle_List'.format(self.parent.parent.dataset.name))
        excelvbox.addWidget(QtWidgets.QLabel('Filename:'))
        excelvbox.addWidget(self.xlsFileName)
        
        self.exlbtn = QtWidgets.QPushButton('Export to Excel')
        self.exlbtn.resize(self.exlbtn.sizeHint())
        self.exlbtn.clicked.connect(self.toExcel)
        
        excelvbox.addWidget(self.exlbtn)
        excelgroup.setLayout(excelvbox)
        
        self.layout.addWidget(excelgroup)

Hackmet's avatar
Hackmet committed
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
#        sqlGroup = QtWidgets.QGroupBox('Export to SQL')
#        sqlLayout = QtWidgets.QVBoxLayout()
#
#        self.sqlbtn = QtWidgets.QPushButton('Export to SQL Database')
#        self.sqlbtn.resize(self.sqlbtn.sizeHint()) 
#        if sqlEnabled:
#            self.sqlbtn.clicked.connect(self.toSQL)
#        else:
#            self.sqlbtn.setDisabled(True)
#        
#        self.sqlExport = None
#
#        sqlLayout.addWidget(self.sqlbtn)
#        sqlGroup.setLayout(sqlLayout)
#        
#        self.layout.addWidget(sqlGroup)
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        self.show()
    
    def toExcel(self):
        requiredcolumns = []        
        self.sizes = np.round(np.array([i[0] if np.isnan(i[2]) else i[2] for i in self.particles]), 1)
        for box in self.checkBoxes:
            if box.isChecked() == True:
                if box.text() != 'Size Classes':
                    requiredcolumns.append(box.text())
                    if box.text() == 'Long Size (µm)':
                        longSize = self.sizes
                    elif box.text() == 'Short Size (µm)':
                        shortSize = np.round(np.array([i[1] if np.isnan(i[3]) else i[3] for i in self.particles]), 1)
                    elif box.text() == 'Area (µm²)':
                        area = np.array([np.round(float(entry[4]), 1) for entry in self.particles])
                else:
                    requiredcolumns.append('0 - 5 µm')
                    requiredcolumns.append('5 - 10 µm')
                    requiredcolumns.append('10 - 20 µm')
                    requiredcolumns.append('20 - 50 µm')
                    requiredcolumns.append('50 - 100 µm')
                    requiredcolumns.append('> 100 µm')
        
        self.finalData = np.array(['nothing to see here, iam a boring placeholder']*((self.polymers.shape[0]+1)*len(requiredcolumns))).reshape(((self.polymers.shape[0]+1), len(requiredcolumns)))

        #create header:
        self.finalData[0, :] = np.array(requiredcolumns)
        self.finalData[0, 0] = 'Polymer Type'
        
        rowindex = 1
        for polymer in np.unique(self.polymers):
            indices = np.where(self.polymers == polymer)[0]
            numentries = int(len(indices))
            
            for colindex, column in enumerate(requiredcolumns):
                if column == 'Polymer Type (mandatory)':
                    self.finalData[rowindex:rowindex+numentries, colindex] = self.polymers[indices]    
                if column == 'Additives':
                    self.finalData[rowindex:rowindex+numentries, colindex] = self.additives[indices]                
                if column == 'Long Size (µm)':
                    self.finalData[rowindex:rowindex+numentries, colindex] = longSize[indices]
                if column == 'Short Size (µm)':
                    self.finalData[rowindex:rowindex+numentries, colindex] = shortSize[indices]
                if column == 'Area (µm²)':
                    self.finalData[rowindex:rowindex+numentries, colindex] = area[indices]
                if column == 'HQI':
                    self.finalData[rowindex:rowindex+numentries, colindex] = self.hqis[indices]
            
            if '> 100 µm' in requiredcolumns:
                ##append size classes
                numPrevCols = len(requiredcolumns) - 6      #number of previous columns
                for tableindex, dataindex in enumerate(indices):    
                    for classindex in range(len(self.sizeClasses)):
                        upLimit = self.sizeClasses[classindex]
                        if classindex == 0: lowLimit = 0
                        else: lowLimit = self.sizeClasses[classindex-1]
                        curSize = self.sizes[dataindex]
                        
                        if  curSize > lowLimit and curSize <= upLimit:
                            self.finalData[rowindex+tableindex, numPrevCols + classindex] = np.int(1)
                        else:
                            self.finalData[rowindex+tableindex, numPrevCols + classindex] = np.int(0)               
            
            rowindex = rowindex + numentries
            
        #dump into excel file
        xlsname = self.directory + '//' + self.xlsFileName.text() + '.xlsx'
        print('exporting excel to:\n file name:  {} in directory: {}'.format(self.xlsFileName.text(), self.directory))
        validFileName = False
        incr = 1
        while not validFileName:
            if not os.path.exists(xlsname):
                validFileName = True
            else:
                xlsname = self.directory + self.xlsFileName.text() + ' {}.xlsx'.format(incr)
                incr += 1
        
        writer = pd.ExcelWriter(xlsname, engine = 'xlsxwriter')
        
        df = pd.DataFrame(self.finalData)
        df.to_excel(writer, sheet_name = 'Individual Particles', header = False, index = False)
        if  '> 100 µm' in requiredcolumns:
            #generate particle statistics report
            report = [['Polymer Type', '0 - 5 µm', '5 - 10 µm', '10 - 20 µm', '20 - 50 µm', '50 - 100 µm', '> 100 µm']]
            
            for polymer in np.unique(self.polymers):
                indices = np.where(self.polymers == polymer)[0]
                classes = np.array([0, 0, 0, 0, 0, 0])
                for size in self.sizes[indices]:
                    if size < 5: classes[0] += 1
                    elif size < 10: classes[1] += 1
                    elif size < 20: classes[2] += 1
                    elif size < 50: classes[3] += 1
                    elif size < 100: classes[4] += 1
                    else: classes[5] += 1
                report.append([polymer, classes[0], classes[1], classes[2], classes[3], classes[4], classes[5]])
            
            report = pd.DataFrame(np.array(report))
            report.to_excel(writer, sheet_name = 'Particle Statistics', header = False, index = False)
        QtWidgets.QMessageBox.about(self, 'Done!', 'Particle Data exported')
        
    def closeEvent(self, event):
        if self.sqlExport is not None:
            self.sqlExport.close()
        event.accept()


class AdditiveViewer(QtWidgets.QWidget):
    def __init__(self, polymername, sortedAdditives):
        super(AdditiveViewer, self).__init__()
        self.setGeometry(200,200, 800, 600)
        self.setWindowTitle('Additives of {}'.format(polymername))
        
        self.layout = QtWidgets.QGridLayout()
        self.setLayout(self.layout)
        
        self.canvas = FigureCanvas(Figure(figsize=(5, 3)))
        self.ax = self.canvas.figure.subplots()
        
        self.layout.addWidget(self.canvas, 0, 0)
        
        self.ax.hist(sortedAdditives)
        self.ax.set_ylabel('Number', fontsize = 15)
        self.ax.tick_params(axis='both', which='both', labelsize=15)


if __name__ == '__main__':
    def run():
        app = QtWidgets.QApplication(sys.argv)
        meas = ParticleAnalysis(None)
        meas.showMaximized()
        ret = app.exec_()
    
    run()