particleInfo.py 15.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# -*- 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/>.
"""
JosefBrandt's avatar
 
JosefBrandt committed
21
#import os
22 23
import numpy as np
import operator
JosefBrandt's avatar
 
JosefBrandt committed
24
#from PyQt5 import QtWidgets, QtCore
25

JosefBrandt's avatar
 
JosefBrandt committed
26 27 28 29 30
#try:
#    from dataset import loadData, recursiveDictCompare
#    print('exported dataset methods from datastats')
#except:
#    print('failed exported dataset methods from datastats')
31

JosefBrandt's avatar
JosefBrandt committed
32 33
class ParticleContainer(object):
    def __init__(self, parent):
JosefBrandt's avatar
 
JosefBrandt committed
34
        super(ParticleContainer, self).__init__()
JosefBrandt's avatar
JosefBrandt committed
35 36 37
        self.parent = parent
        self.particles = []
        self.spectra = None
JosefBrandt's avatar
 
JosefBrandt committed
38
        self.inconsistentParticles = []
JosefBrandt's avatar
JosefBrandt committed
39 40
        
        self.typeHistogram = None
41

JosefBrandt's avatar
JosefBrandt committed
42 43 44
    def initializeParticles(self, numParticles):
        self.particles = []
        for i in range(numParticles):
45 46 47
            newParticle = Particle()
            newParticle.index = i
            self.particles.append(newParticle)
JosefBrandt's avatar
JosefBrandt committed
48
    
49
    def setParticleContours(self, contours):
JosefBrandt's avatar
JosefBrandt committed
50 51 52 53 54 55 56 57
        assert len(self.particles) == len(contours)
        for index, particle in enumerate(self.particles):
            particle.contour = contours[index]
        
    def setParticleStats(self, particlestats):
        assert len(self.particles) == len(particlestats)
        #particlestats is list of [long, short, longellipse, shortellipse, cv2.contourArea(cnt)]
        for index, particle in enumerate(self.particles):
JosefBrandt's avatar
 
JosefBrandt committed
58 59 60 61 62
            particle.longSize_box = float(particlestats[index][0])
            particle.shortSize_box = float(particlestats[index][1])
            particle.longSize_ellipse = float(particlestats[index][2])
            particle.shortSize_ellipse = float(particlestats[index][3])
            particle.area = float(particlestats[index][4])
JosefBrandt's avatar
JosefBrandt committed
63
    
JosefBrandt's avatar
 
JosefBrandt committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77
    def testForInconsistentParticles(self): #i.e., particles that have multiple measurements with different assignments
        self.inconsistentParticles = []
        for particle in self.particles:
            if not particle.measurementsHaveSameOrigAssignment():
                self.inconsistentParticles.append(particle)
        if len(self.inconsistentParticles) > 0:
            print('Warning, inconsistent particles found!')
            for particle in self.inconsistentParticles:
                print(f'Particle with index {particle.index} has the following assignments:')
                for assignment in particle.getOrigMeasurementAssignments():
                    print(assignment)
        else:
            print('All particles have consistent spectra assignments')
    
JosefBrandt's avatar
 
JosefBrandt committed
78 79 80 81 82 83 84 85
    def applyPixelScaleToParticleStats(self, pixelscale):
        for index, particle in enumerate(self.particles):
            particle.longSize_box *= pixelscale
            particle.shortSize_box *= pixelscale
            particle.longSize_ellipse *= pixelscale
            particle.shortSize_ellipse *= pixelscale
            particle.area *= pixelscale**2

JosefBrandt's avatar
JosefBrandt committed
86 87 88 89
    def applyHQITresholdToParticles(self, minHQI):
        for particle in self.particles:
            particle.applyHQITresholdToMeasurements(minHQI)
            
JosefBrandt's avatar
 
JosefBrandt committed
90
    def applyAssignmentListToParticleMeasurements(self, assignmentList):
JosefBrandt's avatar
 
JosefBrandt committed
91 92
        '''AssignmentList is list of spectra assignments in order of spectra indices'''
        indicesOfTransferredAssignments = [None]*len(assignmentList)
JosefBrandt's avatar
 
JosefBrandt committed
93 94 95 96
        for particle in self.particles:
            for meas in particle.getMeasurements():
                scanIndex = meas.getScanIndex()
                meas.setAssignment(assignmentList[scanIndex])
JosefBrandt's avatar
 
JosefBrandt committed
97 98
                indicesOfTransferredAssignments[scanIndex] = scanIndex
        assert not None in indicesOfTransferredAssignments
JosefBrandt's avatar
 
JosefBrandt committed
99
    
JosefBrandt's avatar
 
JosefBrandt committed
100
    def applyHQIListToParticleMeasurements(self, hqiList):
JosefBrandt's avatar
 
JosefBrandt committed
101 102
        '''HQI-List is list of spectra hqis in order of spectra indices'''
        indicesOfTransferredHQIs = [None]*len(hqiList)
JosefBrandt's avatar
 
JosefBrandt committed
103 104 105
        for particle in self.particles:
            for meas in particle.getMeasurements():
                scanIndex = meas.getScanIndex()
JosefBrandt's avatar
 
JosefBrandt committed
106 107 108
                meas.setHQI(hqiList[scanIndex])
                indicesOfTransferredHQIs[scanIndex] = scanIndex
        assert not None in indicesOfTransferredHQIs
JosefBrandt's avatar
 
JosefBrandt committed
109
    
JosefBrandt's avatar
 
JosefBrandt committed
110 111 112 113
    def reassignParticleToAssignment(self, particleIndex, newAssignment):
        particle = self.getParticleOfIndex(particleIndex)
        particle.setAllSpectraToNewAssignment(newAssignment)
    
JosefBrandt's avatar
 
JosefBrandt committed
114 115 116 117
    def getParticleOfIndex(self, index):
        particle = self.particles[index]
        assert particle.index == index, f'particle.index ({particle.index}) does match requested index in particleList ({index})' 
        return particle
JosefBrandt's avatar
 
JosefBrandt committed
118 119 120 121 122 123
    
    def getParticleIndexContainingSpecIndex(self, index):
        for particle in self.particles:
            if index in particle.getMeasurementIndices():
                return particle.index
    
JosefBrandt's avatar
JosefBrandt committed
124 125 126
    def getNumberOfParticles(self):
        return len(self.particles)
    
JosefBrandt's avatar
 
JosefBrandt committed
127 128 129 130 131 132
    def getParticleContours(self):
        contours = [part.contour for part in self.particles]
        return contours
    
    def getParticleContoursByIndex(self, partIndices):
        contours = []
JosefBrandt's avatar
 
JosefBrandt committed
133 134 135
        for index in partIndices:
            particle = self.getParticleOfIndex(index)
            contours.append(particle.contour)
JosefBrandt's avatar
 
JosefBrandt committed
136 137
        return contours
    
JosefBrandt's avatar
 
JosefBrandt committed
138 139 140 141
    def getParticleAssignmentByIndex(self, partIndex):
        particle = self.getParticleOfIndex(partIndex)
        return particle.getParticleAssignment()
    
JosefBrandt's avatar
JosefBrandt committed
142 143 144
    def getMeasurementPixelCoords(self):
        coords = []
        for particle in self.particles:
JosefBrandt's avatar
 
JosefBrandt committed
145
            for measurement in particle.getMeasurements():
JosefBrandt's avatar
JosefBrandt committed
146 147 148
                coords.append([measurement.pixelcoord_x, measurement.pixelcoord_y])
        return coords
    
JosefBrandt's avatar
 
JosefBrandt committed
149 150 151 152 153 154 155
    def getNumberOfParticlesOfAssignment(self, assignment):
        num = 0
        for particle in self.particles:
            if particle.getParticleAssignment() == assignment:
                num += 1
        return num
    
JosefBrandt's avatar
 
JosefBrandt committed
156 157 158 159 160 161 162 163
    def getNumberOfSpectraOfParticle(self, particleIndex):
        particle = self.getParticleOfIndex(particleIndex)
        return particle.getNumberOfMeasurements()

    def getSpectraIndicesOfParticle(self, particleIndex):
        particle = self.getParticleOfIndex(particleIndex)
        return particle.getMeasurementIndices()
        
JosefBrandt's avatar
JosefBrandt committed
164 165 166 167 168 169
    def getListOfParticleAssignments(self):
        particleAssignments = []
        for particle in self.particles:
            particleAssignments.append(particle.getParticleAssignment())
        return particleAssignments
    
JosefBrandt's avatar
 
JosefBrandt committed
170 171 172 173 174 175
    def getListOfHighestHQIs(self):
        hqis = []
        for particle in self.particles:
            hqis.append(particle.getHighestHQI())
        return hqis
    
JosefBrandt's avatar
 
JosefBrandt committed
176 177 178 179
    def getHQIOfSpectrumIndex(self, specIndex):
        for particle in self.particles:
            if specIndex in particle.getMeasurementIndices():
                return particle.getHQIOfMeasurementIndex(specIndex)
JosefBrandt's avatar
 
JosefBrandt committed
180 181
                    
    def getSizesOfAllParticles(self):
JosefBrandt's avatar
JosefBrandt committed
182
        particleSizes = []
JosefBrandt's avatar
 
JosefBrandt committed
183 184
        for particle in self.particles:
            particleSizes.append(particle.getParticleSize())
JosefBrandt's avatar
 
JosefBrandt committed
185
        return particleSizes
JosefBrandt's avatar
 
JosefBrandt committed
186 187 188 189
        
    def getShortSizesOfAllParticles(self):
        shortSizes = []
        for particle in self.particles:
JosefBrandt's avatar
 
JosefBrandt committed
190 191
            shortSizes.append(particle.getShortParticleSize())#
        return shortSizes
JosefBrandt's avatar
 
JosefBrandt committed
192 193 194 195 196 197
    
    def getSizesOfParticleType(self, assignment):
        particleSizes = []
        for particle in self.particles:
            if particle.getParticleAssignment() == assignment:
                particleSizes.append(particle.getParticleSize())
JosefBrandt's avatar
 
JosefBrandt committed
198
        return particleSizes
JosefBrandt's avatar
 
JosefBrandt committed
199
    
JosefBrandt's avatar
 
JosefBrandt committed
200 201
    def getIndicesOfParticleType(self, assignment):
        indices = []
JosefBrandt's avatar
 
JosefBrandt committed
202
        for particle in self.particles:
JosefBrandt's avatar
 
JosefBrandt committed
203 204 205 206 207 208 209
            if particle.getParticleAssignment() == assignment:
                indices.append(particle.index)
        return indices
    
    def getSizeOfParticleByIndex(self, index):
        particle = self.getParticleOfIndex(index)
        return particle.getParticleSize()
JosefBrandt's avatar
JosefBrandt committed
210
    
JosefBrandt's avatar
 
JosefBrandt committed
211 212 213 214
    def getUniquePolymers(self):
        typeHist = self.getTypeHistogram()
        return typeHist.keys()

JosefBrandt's avatar
JosefBrandt committed
215
    def getTypeHistogram(self):
JosefBrandt's avatar
 
JosefBrandt committed
216
        uniquePolymers = np.unique(self.getListOfParticleAssignments())
JosefBrandt's avatar
JosefBrandt committed
217 218 219 220 221
        typehistogram = {i: 0 for i in uniquePolymers}
        for assignment in self.getListOfParticleAssignments():
            typehistogram[assignment] += 1
        ##sort typehistogram, it will be converted into a list!!
        sorted_typehistogram = sorted(typehistogram.items(), key = operator.itemgetter(1), reverse = True)
222
        #convert back to dsetParticlecontoursict
JosefBrandt's avatar
JosefBrandt committed
223
        final_typehistogram = {i[0]: i[1] for i in sorted_typehistogram}
JosefBrandt's avatar
 
JosefBrandt committed
224
        return final_typehistogram
JosefBrandt's avatar
JosefBrandt committed
225
    
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    def mergeParticles(self, particleIndices, newContour, newStats, newAssignment=None):
        newParticle = Particle()
        #copy Measurements
        for index in particleIndices:
            particle = self.getParticleOfIndex(index)
            for meas in particle.getMeasurements():
                if newAssignment is not None:
                    meas.setAssignment(newAssignment)
                    meas.setHQI(100)
                newParticle.addExistingMeasurement(meas)
        
        #set Particle Stats
        long, short, longellipse, shortellipse, area = newStats
        newParticle.longSize_box = long
        newParticle.shortSize_box = short
        newParticle.longSize_ellipse = longellipse
        newParticle.shortSize_ellipse = shortellipse
        newParticle.area = area
        newParticle.contour = newContour
        
        self.removeParticles(particleIndices)
JosefBrandt's avatar
 
JosefBrandt committed
247 248 249
        print('removed particles')
        self.particles.append(newParticle)
        print('added new particle')
250
        self.resetParticleIndices()
JosefBrandt's avatar
 
JosefBrandt committed
251
        print('resetted indices')
252 253
        
    def removeParticles(self, indexList):
JosefBrandt's avatar
 
JosefBrandt committed
254 255 256
        for index in sorted(indexList, reverse=True):
            particle = self.getParticleOfIndex(index)   #just for asserting to have the correct particle!
            del self.particles[index]
257 258 259 260 261
            
    def resetParticleIndices(self):
        for newIndex, particle in enumerate(self.particles):
            particle.index = newIndex
        
JosefBrandt's avatar
JosefBrandt committed
262 263

class Particle(object):
264 265 266
    def __init__(self):
        super(Particle, self).__init__()
        self.index = None
JosefBrandt's avatar
 
JosefBrandt committed
267 268 269 270
        self.longSize_ellipse = np.nan
        self.shortSize_ellipse = np.nan
        self.longSize_box = np.nan
        self.shortSize_box = np.nan
JosefBrandt's avatar
JosefBrandt committed
271 272 273
        self.area = None
        self.contour = None
        self.measurements = []
274 275 276 277
        
    def addExistingMeasurement(self, meas):
        self.measurements.append(meas)
    
JosefBrandt's avatar
JosefBrandt committed
278 279 280 281 282 283 284 285 286 287 288 289
    def addEmptyMeasurement(self):
        self.measurements.append(Measurement())
        indexOfNewMeasurment = len(self.measurements)-1
        return indexOfNewMeasurment
    
    def setMeasurementScanIndex(self, indexOfMeasurment, scanIndex):
        self.measurements[indexOfMeasurment].ramanScanIndex = scanIndex
    
    def setMeasurementPixelCoords(self, indexOfMeasurment, x, y):
        self.measurements[indexOfMeasurment].pixelcoord_x= x
        self.measurements[indexOfMeasurment].pixelcoord_y = y

JosefBrandt's avatar
 
JosefBrandt committed
290 291 292 293 294
    def setAllSpectraToNewAssignment(self, newAssignment):
        for meas in self.measurements:
            meas.setAssignment(newAssignment)
            meas.setHQI(100)

JosefBrandt's avatar
JosefBrandt committed
295
    def getParticleAssignment(self):
JosefBrandt's avatar
 
JosefBrandt committed
296 297 298 299 300 301 302
        return self.getMeasAssignmentWithHighestHQI()   #probably another method could be more suitable...
    
    def getHighestHQI(self):
        hqis = []
        for meas in self.measurements:
            hqis.append(meas.getHQI())
        return max(hqis)
JosefBrandt's avatar
JosefBrandt committed
303
    
JosefBrandt's avatar
 
JosefBrandt committed
304 305 306 307 308 309 310 311 312 313 314
    def getHQIOfMeasurementIndex(self, index):
        for meas in self.measurements:
            if meas.ramanScanIndex == index:
                return meas.getHQI()
    
    def getMeasurementIndices(self):
        indices = []
        for meas in self.measurements:
            indices.append(meas.ramanScanIndex)
        return indices
    
JosefBrandt's avatar
 
JosefBrandt committed
315 316 317 318 319 320 321 322 323 324 325 326
    def getMeasurements(self):
        return self.measurements
    
    def getMeasAssignmentWithHighestHQI(self):
        hqis = []
        assignments = []
        for meas in self.measurements:
            hqis.append(meas.getHQI())
            assignments.append(meas.getAssignment())
        indexOfHighestHQI = hqis.index(max(hqis))
        return assignments[indexOfHighestHQI]
        
JosefBrandt's avatar
JosefBrandt committed
327
    def getParticleSize(self):
JosefBrandt's avatar
 
JosefBrandt committed
328 329 330 331
        if not np.isnan(self.longSize_ellipse):
            size = self.longSize_ellipse
        elif not np.isnan(self.longSize_box):
            size = self.longSize_box
JosefBrandt's avatar
JosefBrandt committed
332 333 334
        else:
            print(f'Error, particle size requested, but not yet set.\nParticle Index is {self.index}')
            raise ValueError
JosefBrandt's avatar
 
JosefBrandt committed
335 336
        assert size is not None, f'Error, size or particle {self.index} is None'
        return round(size)
JosefBrandt's avatar
JosefBrandt committed
337
    
JosefBrandt's avatar
 
JosefBrandt committed
338
    def getShortParticleSize(self):
JosefBrandt's avatar
 
JosefBrandt committed
339
        if not np.isnan(self.shortSize_ellipse):
JosefBrandt's avatar
 
JosefBrandt committed
340
            return round(self.shortSize_ellipse)
JosefBrandt's avatar
 
JosefBrandt committed
341 342
        elif not np.isnan(self.shortSize_box):
            return round(self.shortSize_box)
JosefBrandt's avatar
 
JosefBrandt committed
343 344 345 346
        else:
            print(f'Error, particle size requested, but not yet set.\nParticle Index is {self.index}')
            raise ValueError
    
JosefBrandt's avatar
 
JosefBrandt committed
347 348
    def getNumberOfMeasurements(self):
        return len(self.measurements)
JosefBrandt's avatar
 
JosefBrandt committed
349 350 351
    
    def measurementsHaveSameOrigAssignment(self):
        allResults = [meas.getOrigAssignment() for meas in self.measurements]
JosefBrandt's avatar
JosefBrandt committed
352 353 354 355 356
        if len(np.unique(allResults)) == 1:
            return True
        elif len(np.unique(allResults)) > 1:
            return False

JosefBrandt's avatar
 
JosefBrandt committed
357 358 359 360
    def getOrigMeasurementAssignments(self):
        assignments = [meas.getOrigAssignment() for meas in self.measurements]
        return assignments

JosefBrandt's avatar
JosefBrandt committed
361 362
    def applyHQITresholdToMeasurements(self, minHQI):
        for measurement in self.measurements:
JosefBrandt's avatar
 
JosefBrandt committed
363
            measurement.applyHQIThreshold(minHQI)
JosefBrandt's avatar
JosefBrandt committed
364 365 366 367
    
    
class Measurement(object):
    def __init__(self):
368
        super(Measurement, self).__init__()
JosefBrandt's avatar
JosefBrandt committed
369 370 371 372 373 374 375 376
        self.ramanScanIndex = None
        self.pixelcoord_x= None
        self.pixelcoord_y = None
        
        self.assignment_orig = 'Not Evaluated'
        self.assignment_afterHQI = None
        self.hqi = None
    
JosefBrandt's avatar
 
JosefBrandt committed
377
    def setAssignment(self, assignment):
JosefBrandt's avatar
JosefBrandt committed
378
        self.assignment_orig = assignment
379
        self.applyHQIThreshold()
JosefBrandt's avatar
 
JosefBrandt committed
380 381
        
    def setHQI(self, hqi):
JosefBrandt's avatar
JosefBrandt committed
382 383 384 385
        self.hqi = hqi
        self.applyHQIThreshold()
    
    def applyHQIThreshold(self, minHQI=0):
386 387 388 389 390
        if self.hqi is not None:    #i.e. skip for initial setup, when hqi is not yet aplied...
            if self.hqi >= minHQI:
                self.assignment_afterHQI = self.assignment_orig
            else:
                self.assignment_afterHQI = 'unknown'
JosefBrandt's avatar
 
JosefBrandt committed
391 392 393 394
    
    def getHQI(self):
        return self.hqi
    
JosefBrandt's avatar
JosefBrandt committed
395 396 397 398 399 400
    def getAssignment(self):
        if self.assignment_afterHQI is None:
            return self.assignment_orig
        else:
            return self.assignment_afterHQI
        
JosefBrandt's avatar
 
JosefBrandt committed
401 402 403 404
    def getOrigAssignment(self):
        return self.assignment_orig
    
    def getScanIndex(self):
JosefBrandt's avatar
 
JosefBrandt committed
405
        return self.ramanScanIndex