analysisplots.py 11 KB
Newer Older
JosefBrandt's avatar
 
JosefBrandt committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#!/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/>.
"""
from PyQt5 import QtWidgets, QtGui, QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
26
import numpy as np
JosefBrandt's avatar
 
JosefBrandt committed
27

28
from .colorlegend import getColorFromNameWithSeed
JosefBrandt's avatar
 
JosefBrandt committed
29

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
class SizeHistogramPlot(QtWidgets.QGroupBox):
    def __init__(self, dataset):
        super(SizeHistogramPlot, self).__init__()
        self.dataset = dataset
        
        self.minX = 3
        self.maxX = 1E4
        self.fontsize = 15
        
        layout = QtWidgets.QHBoxLayout()
        self.setLayout(layout)
        self.sizeHistogramCanvas = FigureCanvas(Figure())
        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)
        histNavigation.setFixedWidth(50)
        layout.addWidget(histNavigation)
        layout.addWidget(self.sizeHistogramCanvas)
    
    def drawHistograms(self, listOfHistograms):
        if type(listOfHistograms) != list:
            assert type(listOfHistograms) == SizeHistogramData
            listOfHistograms = [listOfHistograms]
        
        self.resetPlotFormat()
        self.adjustPlotLimits(listOfHistograms)
        
        for histData in listOfHistograms:
            self.drawHistogram(histData)
        
        self.drawLegend()
        self.sizeHistogramCanvas.draw()
        
    def resetPlotFormat(self):
        self.sizeHist_ax.clear()
        self.sizeHist_ax.axis('on')
        self.sizeHist_ax.tick_params(axis='both', which='both', labelsize = self.fontsize)
        self.sizeHist_ax.set_xlabel('Size (µm)', fontsize = self.fontsize)
        self.sizeHist_ax.set_ylabel('Number', fontsize = self.fontsize)
        self.sizeHist_ax.set_title('Size Distribution', fontsize=self.fontsize)
        
    def adjustPlotLimits(self, listOfHistograms):
        xmin, xmax = None, None
        for histData in listOfHistograms:
            if xmin is None:
                xmin = np.clip(10**histData.minSizeExponent, self.minX, self.maxX)
                xmax = np.clip(10**histData.maxSizeExponent, self.minX, self.maxX)
            else:
                currentXMin = np.clip(10**histData.minSizeExponent, self.minX, self.maxX)
                currentXMax = np.clip(10**histData.maxSizeExponent, self.minX, self.maxX)
                xmin = min(xmin, currentXMin)
                xmax = max(xmax, currentXMax)
        
        self.sizeHist_ax.set_xlim(xmin, xmax)
    
    def drawHistogram(self, histData):
        label = histData.label
        x_values = histData.sizeHist_binCenters
        y_values = histData.sizeHist_abundancies
        color = getColorFromNameWithSeed(label, self.dataset.colorSeed, base255=False)
        self.sizeHist_ax.semilogx(x_values, y_values, label=label, color=color)    
        
    def drawLegend(self):
        self.sizeHist_ax.legend(prop = {'size': self.fontsize})


class SizeHistogramData(object):
    def __init__(self, label, listOfSizes):
        self.label = label
        self.listOfSizes = listOfSizes
        
        self.minSizeExponent = 0.1
        self.maxSizeExponent = 3
        self.numBins = 20
        
        self.sizeHist_binCenters = None
        self.sizeHist_abundancies = None
        
        self.createSizeHistogramData()
    
    def createSizeHistogramData(self):
        assert self.listOfSizes is not None
        bins = np.logspace(self.minSizeExponent, self.maxSizeExponent, self.numBins)
        self.sizeHist_abundancies, binEdges = np.histogram(self.listOfSizes, bins)
        self.sizeHist_binCenters = self.getBinCenters(binEdges)
    
    def getBinCenters(self, binEdges):
        binCenters = []
        for i in range(self.numBins-1):
            currentCenter = np.mean((binEdges[i], binEdges[i+1]))
            binCenters.append(currentCenter)
        return binCenters
    
                
class TypeHistogramPlot(QtWidgets.QScrollArea):
    indexClicked = QtCore.pyqtSignal(int)
    def __init__(self, dataset):
        super(TypeHistogramPlot, self).__init__()
        self.dataset = dataset
        
        self.view = QtWidgets.QWidget(self)
        self.view.setCursor(QtGui.QCursor(QtCore.Qt.WhatsThisCursor))
        self.view.setMinimumWidth(250)
        
        group = QtWidgets.QGroupBox('Polymer Type Distribution', self.view)
        self.indicatorbox = QtWidgets.QVBoxLayout()
        self.indicatorbox.setContentsMargins(5,5,5,5)
        group.setLayout(self.indicatorbox)
        
        hbox = QtWidgets.QHBoxLayout()
        hbox.addWidget(group)
        self.view.setLayout(hbox)
        self.setWidgetResizable(True)
        self.setWidget(self.view)
        self.setAlignment(QtCore.Qt.AlignHCenter)
        self.abundancyIndicators = []
        
    def updateTypeHistogram(self, typeHistogram):
        self.resetPlot()
        
        colorList = []
        abundancyList = []
        labelList = []
        for polymType in typeHistogram:
            text = f'{typeHistogram[polymType]} x {polymType}'
            labelList.append(text)
            abundancyList.append(typeHistogram[polymType])
            curColor = getColorFromNameWithSeed(polymType, self.dataset.colorSeed)
            colorList.append(QtGui.QColor(*curColor))
        
        types = list(zip(abundancyList, labelList, colorList))
        
        numtotal= sum(abundancyList)
        
        for index, entry in enumerate(types):
            num, text, color = entry
            indicator = AbundancyIndicator(num, numtotal, color, text)
            self.indicatorbox.addWidget(indicator)
            indicator.clicked.connect(self._getIndexFunction(index))
            self.abundancyIndicators.append(indicator)
            
        self.indicatorbox.addStretch()
        self.view.update()
        
    def resetPlot(self):
        for indicator in self.abundancyIndicators:
            self.indicatorbox.removeWidget(indicator)
            indicator.setParent(None)
            indicator.destroy()
        self.indicatorbox.takeAt(0)
        self.abundancyIndicators = []
    
    def _getIndexFunction(self, index):
            return lambda : self.indexClicked.emit(index)

class AbundancyIndicator(QtWidgets.QPushButton):
JosefBrandt's avatar
 
JosefBrandt committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    def __init__(self, number, numtotal, color, text, parent=None):
        super().__init__(parent)
        self.number = number
        self.numtotal = numtotal
        self.color = color
        self.text = text
        self.setFixedHeight(30)
        
    def paintEvent(self, event):
        r = self.number/self.numtotal
        width = self.width()
        height = self.height()
        
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.setBrush(QtCore.Qt.white)
        qp.drawRoundedRect(0, 0, width, height, 5. ,5.)
        qp.setPen(self.color)
        qp.setBrush(self.color)
        qp.drawRoundedRect(0, 0, int(width*r), height, 5. ,5.)
        qp.setPen(QtCore.Qt.black)
        qp.setBrush(QtCore.Qt.NoBrush)
        qp.drawRoundedRect(0, 0, width, height, 5. ,5.)
        font = qp.font()
        font.setPointSize(13)
        font.setStyleStrategy(QtGui.QFont.NoAntialias)
        font.setWeight(0)
        qp.setFont(font)
        qp.setCompositionMode(QtGui.QPainter.RasterOp_SourceXorDestination)
        qp.setPen(QtCore.Qt.white)
        qp.drawText(5, 0, width-10, height, QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter, 
                    self.text)
        qp.end()
        

class SpectraPlot(QtWidgets.QGroupBox):
    def __init__(self, dataset):
        super(SpectraPlot, self).__init__()
        self.dataset = dataset
        self.spectra = None
228
        self.fontsize = 15
JosefBrandt's avatar
 
JosefBrandt committed
229 230 231 232
        
        layout = QtWidgets.QHBoxLayout()
        self.canvas = FigureCanvas(Figure())
        self.spec_axis = self.canvas.figure.subplots()
JosefBrandt's avatar
JosefBrandt committed
233
        self.reference_axis = self.spec_axis.twinx()
JosefBrandt's avatar
 
JosefBrandt committed
234 235 236 237 238 239 240 241 242
        self.canvas.figure.subplots_adjust(left=0.1, top=0.93, bottom=0.15, right=0.9)
        specNavigation = NavigationToolbar(self.canvas, self)
        specNavigation.setOrientation(QtCore.Qt.Vertical)
        specNavigation.setFixedWidth(50)
        
        layout.addWidget(specNavigation)
        layout.addWidget(self.canvas)
        self.setLayout(layout)
        
JosefBrandt's avatar
JosefBrandt committed
243 244
    def loadSpectraAndInitializeSpecPlot(self):
        self.spectra = self.dataset.particleContainer.getSpectraFromDisk()
JosefBrandt's avatar
 
JosefBrandt committed
245 246
        self.canvas.draw()
        
247
    def updateParticleSpectrum(self, specIndex, assignment, hqi):
JosefBrandt's avatar
JosefBrandt committed
248 249 250
        #draw Sample Spectrum
        self.spec_axis.axis("on")
        self.spec_axis.clear()
251 252 253
        self.spec_axis.tick_params(axis='both', which='both', labelsize = self.fontsize)
        self.spec_axis.set_xlabel('Wavenumber (cm-1)', fontsize = self.fontsize)
        self.spec_axis.set_ylabel('Counts', fontsize = self.fontsize)
JosefBrandt's avatar
JosefBrandt committed
254
        
JosefBrandt's avatar
 
JosefBrandt committed
255
        if self.spectra is not None:
256
            specInfo = f'ScanPoint Number {specIndex+1}, with assignment {assignment} (hqi = {hqi})'
JosefBrandt's avatar
 
JosefBrandt committed
257
            self.spec_axis.plot(self.spectra[:, 0], self.spectra[:, specIndex+1])
258
            self.spec_axis.set_title(specInfo, fontsize = self.fontsize)
JosefBrandt's avatar
 
JosefBrandt committed
259
            self.spec_axis.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
260
            
JosefBrandt's avatar
 
JosefBrandt committed
261 262 263 264 265 266 267 268 269 270 271
            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_axis.set_ybound(0.9*y_min, 1.1*y_max)
            
        self.canvas.draw()
    
    def updateReferenceSpectrum(self, ref_wavenumber, ref_intensity):
        #draw Reference
        self.reference_axis.clear()
272
        self.reference_axis.tick_params(axis='both', which='both', labelsize = self.fontsize)
JosefBrandt's avatar
 
JosefBrandt committed
273
        self.reference_axis.plot(ref_wavenumber, ref_intensity, color = 'r')
274
        self.reference_axis.set_ylabel('Ref. Intensity', fontsize = self.fontsize, color = 'r')
JosefBrandt's avatar
 
JosefBrandt committed
275 276 277
        self.reference_axis.tick_params('y', colors = 'r')
        self.reference_axis.set_xbound(100, (3400 if self.spectra[-1, 0] > 3400 else self.spectra[-1, 0]))
        
278
        self.canvas.draw()