particleContainer.py 17.3 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
# -*- 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
import operator
23 24
import os
from PyQt5 import QtWidgets
25
from typing import List, TYPE_CHECKING
26

27
from .particleAndMeasurement import Particle, Measurement
Elisa Kanaki's avatar
Elisa Kanaki committed
28
from .particleCharacterization import calculateFTIRAperturesForParticle, getFibreDimension
Josef Brandt's avatar
Josef Brandt committed
29 30
specImportEnabled: bool = True
try:
31
    from ..analysis import importSpectra
Josef Brandt's avatar
Josef Brandt committed
32 33 34
except ModuleNotFoundError:
    specImportEnabled = False

35 36
if TYPE_CHECKING:
    from ..dataset import DataSet
37
    from ..scenePyramid import ScenePyramid
38

39

JosefBrandt's avatar
JosefBrandt committed
40
class ParticleContainer(object):
Josef Brandt's avatar
Josef Brandt committed
41
    def __init__(self):
JosefBrandt's avatar
 
JosefBrandt committed
42
        super(ParticleContainer, self).__init__()
Josef Brandt's avatar
Josef Brandt committed
43
        self.datasetParent: 'DataSet' = None
44 45 46
        self.particles: List[Particle] = []
        self.measurements: List[Measurement] = []
        self.inconsistentParticles: List[Particle] = []
Josef Brandt's avatar
Josef Brandt committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

    def setDataSet(self, ds):
        """
        dynamically sets a reference to the dataset containing this particle container
        :param ds:
        :return:
        """
        self.datasetParent = ds

    def unsetDataSet(self):
        """
        is called before dataset is saved, preventing pickle to resolve this reference to dataset into
        a copy of it (baking its data into the save file)
        :return:
        """
        self.datasetParent = None

Josef Brandt's avatar
Josef Brandt committed
64
    def addEmptyMeasurement(self) -> int:
JosefBrandt's avatar
JosefBrandt committed
65 66 67
        newMeas = Measurement()
        self.measurements.append(newMeas)
        return self.measurements.index(newMeas)
68
    
Josef Brandt's avatar
Josef Brandt committed
69
    def clearParticles(self) -> None:
70 71
        self.particles = []
    
Josef Brandt's avatar
Josef Brandt committed
72
    def clearMeasurements(self) -> None:
73
        self.measurements = []
74 75
        for particle in self.particles:
            particle.measurements = []
76

77
    def setMeasurementScanIndex(self, indexOfMeasurment, scanIndex):
78 79 80 81 82 83
        """
        associates measurment/contour/particle with scan result via its (scan) index
        :param indexOfMeasurment:
        :param scanIndex:
        :return:
        """
84
        self.measurements[indexOfMeasurment].specScanIndex = scanIndex
85 86 87 88 89
    
    def setMeasurementPixelCoords(self, indexOfMeasurment, x, y):
        self.measurements[indexOfMeasurment].pixelcoord_x = x
        self.measurements[indexOfMeasurment].pixelcoord_y = y
    
Josef Brandt's avatar
Josef Brandt committed
90
    def getMeasurementScanindex(self, indexOfMeasurement) -> int:
JosefBrandt's avatar
JosefBrandt committed
91
        return self.measurements[indexOfMeasurement].getScanIndex()
Josef Brandt's avatar
Josef Brandt committed
92 93

    def getSpectraFromDisk(self) -> np.ndarray:
JosefBrandt's avatar
JosefBrandt committed
94
        spectra = None
Josef Brandt's avatar
Josef Brandt committed
95 96 97 98 99 100 101 102
        if specImportEnabled:
            specPath = self.datasetParent.getSpectraFileName()
            if os.path.exists(specPath):
                spectra = np.load(specPath)
            else:
                fname = QtWidgets.QFileDialog.getOpenFileName(QtWidgets.QWidget(), 'Select Spectra File',
                                                              self.datasetParent.path, 'text file (*.txt)')[0]
                if fname:
JosefBrandt's avatar
JosefBrandt committed
103
                    try:
Josef Brandt's avatar
Josef Brandt committed
104 105 106 107 108 109 110 111 112 113
                        instruments = importSpectra.listInstruments()
                        instrument, okPressed = QtWidgets.QInputDialog.getItem(QtWidgets.QWidget(), "File format",
                                                                               "Select instrument:", instruments, 0, False)
                        if okPressed and instrument:
                            spectra, spectraNames = importSpectra.chooseInstrument(instrument, fname)
                    except (ValueError, ImportError):
                        QtWidgets.QMessageBox.warning(QtWidgets.QWidget(), 'Error', 'Unknown format, no spectra loaded.')

                if spectra is not None:
                    np.save(self.datasetParent.getSpectraFileName(), spectra)
JosefBrandt's avatar
JosefBrandt committed
114
        return spectra
115
    
JosefBrandt's avatar
JosefBrandt committed
116 117 118
    def initializeParticles(self, numParticles):
        self.particles = []
        for i in range(numParticles):
119 120 121
            newParticle = Particle()
            newParticle.index = i
            self.particles.append(newParticle)
JosefBrandt's avatar
JosefBrandt committed
122
    
123
    def setParticleContours(self, contours):
JosefBrandt's avatar
JosefBrandt committed
124 125 126 127 128
        assert len(self.particles) == len(contours)
        for index, particle in enumerate(self.particles):
            particle.contour = contours[index]
        
    def setParticleStats(self, particlestats):
129
        assert len(self.particles) == len(particlestats), f'numParticles = {len(self.particles)}, len partStats = {len(particlestats)}'
JosefBrandt's avatar
JosefBrandt committed
130
        for index, particle in enumerate(self.particles):
131
            particle.__dict__.update(particlestats[index].__dict__)
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

    def updateFTIRApertures(self, pyramid: 'ScenePyramid', progressbar: QtWidgets.QProgressDialog = None) -> None:
        """
        Calculates FTIR Apertures if they were not already calculated...
        """
        if progressbar is not None:
            progressbar.setWindowTitle("Calculating Particle Apertures")
            progressbar.setMaximum(len(self.particles)-1)
            progressbar.setValue(0)

        for i, particle in enumerate(self.particles):
            if not hasattr(particle, 'aperture'):
                particle.aperture = calculateFTIRAperturesForParticle(particle, pyramid)
            elif particle.aperture is None:
                particle.aperture = calculateFTIRAperturesForParticle(particle, pyramid)
            progressbar.setValue(i)

Josef Brandt's avatar
Josef Brandt committed
149 150
    def testForInconsistentParticleAssignments(self):
        # Find particles that have multiple measurements with different assignments
JosefBrandt's avatar
 
JosefBrandt committed
151 152 153 154 155 156 157 158 159 160 161 162 163
        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
164 165 166 167 168 169 170 171
    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
172 173 174 175
    def applyHQITresholdToParticles(self, minHQI):
        for particle in self.particles:
            particle.applyHQITresholdToMeasurements(minHQI)
            
JosefBrandt's avatar
 
JosefBrandt committed
176
    def applyAssignmentListToParticleMeasurements(self, assignmentList):
JosefBrandt's avatar
 
JosefBrandt committed
177
        '''AssignmentList is list of spectra assignments in order of spectra indices'''
JosefBrandt's avatar
JosefBrandt committed
178 179 180 181
        assert len(assignmentList) == len(self.measurements), f'assertion error in assignment of results: {len(assignmentList)} results for {len(self.measurements)} spectra...'
        for meas in self.measurements:
            scanIndex = meas.getScanIndex()
            meas.setAssignment(assignmentList[scanIndex])
Josef Brandt's avatar
Josef Brandt committed
182 183 184 185 186 187 188

    def applyDatabaseResultsToParticleMeasurements(self, resultDictList: list) -> None:
        """
        The resultDictList has a dict for each measurement, containing multiple database results.
        Key: HQI, Val: Resultname
        """
        pass
JosefBrandt's avatar
 
JosefBrandt committed
189
    
JosefBrandt's avatar
 
JosefBrandt committed
190
    def applyHQIListToParticleMeasurements(self, hqiList):
JosefBrandt's avatar
 
JosefBrandt committed
191
        '''HQI-List is list of spectra hqis in order of spectra indices'''
JosefBrandt's avatar
JosefBrandt committed
192 193 194 195
        assert len(hqiList) == len(self.measurements), f'assertion error in assignment of hqis: {len(hqiList)} results for {len(self.measurements)} spectra...'
        for meas in self.measurements:
            scanIndex = meas.getScanIndex()
            meas.setHQI(hqiList[scanIndex])
JosefBrandt's avatar
 
JosefBrandt committed
196 197
    
    def getParticleOfIndex(self, index):
JosefBrandt's avatar
JosefBrandt committed
198 199
        try:
            particle = self.particles[index]
200
            assert particle.index == index, f'particle.index ({particle.index}) does not match requested index in particleList ({index})' 
JosefBrandt's avatar
JosefBrandt committed
201 202 203 204
        except:
            print('failed getting particle')
            print('requested Index:', index)
            print('len particles', len(self.particles))
205 206
            raise
        
JosefBrandt's avatar
 
JosefBrandt committed
207
        return particle
Josef Brandt's avatar
Josef Brandt committed
208 209 210 211 212 213 214 215 216 217 218 219 220

    def getParticleOfUID(self, uid):
        try:
            for particle in self.particles:
                if uid == particle.uid:
                    break
        except:
            print('failed getting particle')
            print('requested Index:', uid)
            print('len particles', len(self.particles))
        assert particle.uid == uid, f'particle.index ({particle.uid}) does match requested index in particleList ({uid})'
        return particle

JosefBrandt's avatar
 
JosefBrandt committed
221 222 223 224 225
    def getParticleIndexContainingSpecIndex(self, index):
        for particle in self.particles:
            if index in particle.getMeasurementIndices():
                return particle.index
    
JosefBrandt's avatar
JosefBrandt committed
226 227 228
    def getNumberOfParticles(self):
        return len(self.particles)
    
JosefBrandt's avatar
JosefBrandt committed
229 230 231
    def getNumberOfMeasurements(self):
        return len(self.measurements)
    
JosefBrandt's avatar
 
JosefBrandt committed
232 233 234 235 236 237
    def getParticleContours(self):
        contours = [part.contour for part in self.particles]
        return contours
    
    def getParticleContoursByIndex(self, partIndices):
        contours = []
JosefBrandt's avatar
 
JosefBrandt committed
238 239 240
        for index in partIndices:
            particle = self.getParticleOfIndex(index)
            contours.append(particle.contour)
JosefBrandt's avatar
 
JosefBrandt committed
241 242
        return contours
    
243 244 245 246 247 248 249
    def getIndicesOfColoredNotUnknownParticles(self):
        coloredParticleIndices = []
        for particle in self.particles:
            if particle.getParticleAssignment() != 'unknown' and particle.color not in ['white', 'non-determinable']:
                coloredParticleIndices.append(particle.index)
        return coloredParticleIndices
    
JosefBrandt's avatar
 
JosefBrandt committed
250 251 252
    def getParticleAssignmentByIndex(self, partIndex):
        particle = self.getParticleOfIndex(partIndex)
        return particle.getParticleAssignment()
Josef Brandt's avatar
Josef Brandt committed
253 254 255 256

    def getParticleAssignmentByUID(self, uid):
        particle = self.getParticleOfUID(uid)
        return particle.getParticleAssignment()
JosefBrandt's avatar
 
JosefBrandt committed
257
    
Josef Brandt's avatar
Josef Brandt committed
258 259
    def getMeasurementPixelCoords(self) -> list:
        coords: list = []
260
        for meas in self.measurements:
261
            coords.append([meas.pixelcoord_x, meas.pixelcoord_y])
JosefBrandt's avatar
JosefBrandt committed
262
        return coords
Josef Brandt's avatar
Josef Brandt committed
263 264 265 266 267 268 269 270

    def getApertureCenterCoords(self) -> list:
        coords: list = []
        for particle in self.particles:
            assert particle.aperture is not None, 'Aperture for particle was not set!'
            coords.append([particle.aperture.centerX, particle.aperture.centerY])
        return coords

JosefBrandt's avatar
 
JosefBrandt committed
271 272 273 274 275 276 277
    def getNumberOfParticlesOfAssignment(self, assignment):
        num = 0
        for particle in self.particles:
            if particle.getParticleAssignment() == assignment:
                num += 1
        return num
    
JosefBrandt's avatar
 
JosefBrandt committed
278 279 280 281 282 283 284
    def getNumberOfSpectraOfParticle(self, particleIndex):
        particle = self.getParticleOfIndex(particleIndex)
        return particle.getNumberOfMeasurements()

    def getSpectraIndicesOfParticle(self, particleIndex):
        particle = self.getParticleOfIndex(particleIndex)
        return particle.getMeasurementIndices()
Josef Brandt's avatar
Josef Brandt committed
285 286 287 288

    def getSpectraIndicesOfParticleByUID(self, particleUID):
        particle = self.getParticleOfUID(particleUID)
        return particle.getMeasurementIndices()
JosefBrandt's avatar
 
JosefBrandt committed
289
        
JosefBrandt's avatar
JosefBrandt committed
290 291 292 293 294 295
    def getListOfParticleAssignments(self):
        particleAssignments = []
        for particle in self.particles:
            particleAssignments.append(particle.getParticleAssignment())
        return particleAssignments
    
JosefBrandt's avatar
 
JosefBrandt committed
296 297 298 299 300 301
    def getListOfHighestHQIs(self):
        hqis = []
        for particle in self.particles:
            hqis.append(particle.getHighestHQI())
        return hqis
    
JosefBrandt's avatar
 
JosefBrandt committed
302 303 304 305
    def getHQIOfSpectrumIndex(self, specIndex):
        for particle in self.particles:
            if specIndex in particle.getMeasurementIndices():
                return particle.getHQIOfMeasurementIndex(specIndex)
JosefBrandt's avatar
 
JosefBrandt committed
306 307
                    
    def getSizesOfAllParticles(self):
JosefBrandt's avatar
JosefBrandt committed
308
        particleSizes = []
JosefBrandt's avatar
 
JosefBrandt committed
309 310
        for particle in self.particles:
            particleSizes.append(particle.getParticleSize())
JosefBrandt's avatar
 
JosefBrandt committed
311
        return particleSizes
JosefBrandt's avatar
 
JosefBrandt committed
312 313 314 315
        
    def getShortSizesOfAllParticles(self):
        shortSizes = []
        for particle in self.particles:
JosefBrandt's avatar
JosefBrandt committed
316
            shortSizes.append(particle.getShortParticleSize())
JosefBrandt's avatar
 
JosefBrandt committed
317
        return shortSizes
JosefBrandt's avatar
 
JosefBrandt committed
318
    
JosefBrandt's avatar
JosefBrandt committed
319 320 321 322 323 324
    def getAreasOfAllParticles(self):
        areas = []
        for particle in self.particles:
            areas.append(particle.getArea())
        return areas
    
325 326 327 328 329 330
    def getColorsOfAllParticles(self):
        colors = []
        for particle in self.particles:
            colors.append(particle.color)
        return colors
    
331 332 333 334 335 336
    def getShapesOfAllParticles(self):
        shapes = []
        for particle in self.particles:
            shapes.append(particle.shape)
        return shapes
    
337 338 339 340
    def getParticleColorByIndex(self, particleIndex):
        particle = self.getParticleOfIndex(particleIndex)
        return particle.color
    
341 342 343
    def getParticleShapeByIndex(self, particleIndex):
        particle = self.getParticleOfIndex(particleIndex)
        return particle.shape
Josef Brandt's avatar
Josef Brandt committed
344 345 346 347 348 349 350 351 352

    def getParticleIndexByUID(self, uid):
        for idx, particle in enumerate(self.particles):
            if uid == particle.uid:
                break

        assert uid == particle.uid
        return idx

JosefBrandt's avatar
 
JosefBrandt committed
353 354 355 356 357
    def getSizesOfParticleType(self, assignment):
        particleSizes = []
        for particle in self.particles:
            if particle.getParticleAssignment() == assignment:
                particleSizes.append(particle.getParticleSize())
JosefBrandt's avatar
 
JosefBrandt committed
358
        return particleSizes
JosefBrandt's avatar
 
JosefBrandt committed
359
    
JosefBrandt's avatar
 
JosefBrandt committed
360 361
    def getIndicesOfParticleType(self, assignment):
        indices = []
JosefBrandt's avatar
 
JosefBrandt committed
362
        for particle in self.particles:
JosefBrandt's avatar
 
JosefBrandt committed
363 364 365
            if particle.getParticleAssignment() == assignment:
                indices.append(particle.index)
        return indices
Josef Brandt's avatar
Josef Brandt committed
366 367 368 369 370 371 372 373

    def getUIDsOfParticleType(self, assignment):
        ids = []
        for particle in self.particles:
            if particle.getParticleAssignment() == assignment:
                ids.append(particle.uid)
        return ids

JosefBrandt's avatar
 
JosefBrandt committed
374 375 376
    def getSizeOfParticleByIndex(self, index):
        particle = self.getParticleOfIndex(index)
        return particle.getParticleSize()
JosefBrandt's avatar
JosefBrandt committed
377
    
JosefBrandt's avatar
 
JosefBrandt committed
378 379 380 381
    def getUniquePolymers(self):
        typeHist = self.getTypeHistogram()
        return typeHist.keys()

JosefBrandt's avatar
JosefBrandt committed
382
    def getTypeHistogram(self):
JosefBrandt's avatar
 
JosefBrandt committed
383
        uniquePolymers = np.unique(self.getListOfParticleAssignments())
JosefBrandt's avatar
JosefBrandt committed
384 385 386
        typehistogram = {i: 0 for i in uniquePolymers}
        for assignment in self.getListOfParticleAssignments():
            typehistogram[assignment] += 1
387
        # sort typehistogram, it will be converted into a list!!
JosefBrandt's avatar
JosefBrandt committed
388
        sorted_typehistogram = sorted(typehistogram.items(), key = operator.itemgetter(1), reverse = True)
389
        # convert back to dsetParticlecontoursict
JosefBrandt's avatar
JosefBrandt committed
390
        final_typehistogram = {i[0]: i[1] for i in sorted_typehistogram}
JosefBrandt's avatar
 
JosefBrandt committed
391
        return final_typehistogram
JosefBrandt's avatar
JosefBrandt committed
392
    
393 394 395 396 397
    def reassignParticleToAssignment(self, particleIndex, newAssignment):
        particle = self.getParticleOfIndex(particleIndex)
        particle.setAllSpectraToNewAssignment(newAssignment)
        particle.wasManuallyEdited = True
    
398 399 400
    def changeParticleColor(self, index, newColor):
        particle = self.getParticleOfIndex(index)
        particle.color = newColor
401
        particle.wasManuallyEdited = True
Josef Brandt's avatar
Josef Brandt committed
402

403 404
    def changeParticleShape(self, index, newShape):
        particle = self.getParticleOfIndex(index)
Josef Brandt's avatar
Josef Brandt committed
405 406

        if 'fibre' == newShape:
Elisa Kanaki's avatar
Elisa Kanaki committed
407
            particle.longSize, particle.shortSize = getFibreDimension(particle.contour)
Josef Brandt's avatar
Josef Brandt committed
408 409 410
            particle.longSize *= self.datasetParent.getPixelScale()
            particle.shortSize *= self.datasetParent.getPixelScale()

411
        particle.shape = newShape
412
        particle.wasManuallyEdited = True
413
    
Josef Brandt's avatar
Josef Brandt committed
414
    def addMergedParticle(self, particleIndices, newContour, newStats, newAssignment=None) -> Particle:
415
        newParticle = Particle()
416
        newParticle.contour = newContour
Josef Brandt's avatar
Josef Brandt committed
417
        # copy Measurements
418 419 420 421 422 423
        for index in particleIndices:
            particle = self.getParticleOfIndex(index)
            for meas in particle.getMeasurements():
                if newAssignment is not None:
                    meas.setAssignment(newAssignment)
                    meas.setHQI(100)
424
                newParticle.addMeasurement(meas)
425 426

        newParticle.__dict__.update(newStats.__dict__)
427
        newParticle.wasManuallyEdited = True
JosefBrandt's avatar
 
JosefBrandt committed
428
        self.particles.append(newParticle)
Josef Brandt's avatar
Josef Brandt committed
429 430 431 432 433 434
        return newParticle

    def removeParticles(self, indices):
        assert isinstance(indices, list)
        for idx in indices:
            self.removeParticle(idx)
435
        
JosefBrandt's avatar
JosefBrandt committed
436 437 438
    def removeParticle(self, index):
        particle = self.getParticleOfIndex(index)   #just for asserting to have the correct particle!
        del self.particles[index]
439 440 441
            
    def resetParticleIndices(self):
        for newIndex, particle in enumerate(self.particles):
Josef Brandt's avatar
Josef Brandt committed
442
            particle.index = newIndex