evaluation.py 11 KB
Newer Older
1 2 3 4 5 6 7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 13:57:28 2020

@author: luna
"""
8
import pickle
Josef Brandt's avatar
Josef Brandt committed
9
import sys
10
import os
11
import numpy as np
12
import matplotlib.pyplot as plt
13

14
from helpers import ParticleBinSorter
Josef Brandt's avatar
Josef Brandt committed
15 16
import methods as meth
import geometricMethods as gmeth
17
import chemometricMethods as cmeth
Josef Brandt's avatar
Josef Brandt committed
18 19
sys.path.append("C://Users//xbrjos//Desktop//Python")
from gepard import dataset
20

Josef Brandt's avatar
Josef Brandt committed
21

Josef Brandt's avatar
Josef Brandt committed
22 23 24 25 26
def get_name_from_directory(dirPath: str) -> str:
    return str(os.path.basename(dirPath).split('.')[0])


class TotalResults(object):
27 28 29 30 31
    # methods: list = [meth.RandomSampling, meth.SizeBinFractioning, gmeth.CrossBoxSubSampling,
    #                  gmeth.SpiralBoxSubsampling, cmeth.ChemometricSubsampling]
    # measuredFractions: list = [0.01, 0.05, 0.1, 0.15, 0.2, 0.5, 0.75, 0.9]
    # measuredFractions: list = [0.1, 0.15, 0.2, 0.5, 0.75, 0.9]
    measuredFractions: list = [0.1, 0.3, 0.5, 0.7, 0.9]
Josef Brandt's avatar
Josef Brandt committed
32 33 34 35 36

    def __init__(self):
        super(TotalResults, self).__init__()
        self.sampleResults: list = []

37
    def add_sample(self, filePath: str):
Josef Brandt's avatar
Josef Brandt committed
38 39 40 41 42
        """
        Adds a new sampleResult object, if a .pkl file is given and if the sample name is not already present.
        :param filePath:
        :return:
        """
43
        newResult: SampleResult = None
Josef Brandt's avatar
Josef Brandt committed
44 45 46 47
        sampleName: str = get_name_from_directory(filePath)
        presentSampleNames: list = [res.sampleName for res in self.sampleResults]
        if sampleName not in presentSampleNames:
            if os.path.basename(filePath).split('.')[-1] == 'pkl':
48 49 50 51
                newResult = SampleResult(filePath)
                self.sampleResults.append(newResult)

        return newResult
Josef Brandt's avatar
Josef Brandt committed
52

53
    def update_all(self, force: bool = False) -> None:
Josef Brandt's avatar
Josef Brandt committed
54 55
        """
        Updates all samples with all methods and all fractions
56
        :param force: Wether to force an update of an already existing method.
Josef Brandt's avatar
Josef Brandt committed
57 58
        :return:
        """
59
        for index, sample in enumerate(self.sampleResults):
Josef Brandt's avatar
Josef Brandt committed
60
            sample.load_dataset()
61
            for fraction in self.measuredFractions:
Josef Brandt's avatar
Josef Brandt committed
62 63
                possibleMethods = self._get_methods_for_fraction(sample.dataset, fraction)
                for curMethod in possibleMethods:
64
                    print(f'updating {sample.sampleName} with {curMethod.label} at fraction {fraction}')
65
                    sample.update_result_with_method(curMethod, force=force)
66
            print(f'processed {index+1} of {len(self.sampleResults)} samples')
Josef Brandt's avatar
Josef Brandt committed
67

68
    def get_error_vs_fraction_data(self, attributes: list = [], methods: list = []) -> dict:
69 70
        """
        Returns Dict: Key: Method Label, Value: (Dict: Key:Measured Fraction, Value: averaged MPCountError over all samples)
71 72
        :param attributes: A list of attributes that should be used for filtering the samples. Only samples with an
        attribute from within that list are considered.
73 74 75 76
        :return:
        """
        result: dict = {}
        for sample in self.sampleResults:
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
            sample: SampleResult = sample
            if attributes == [] or sample.has_any_attribute(attributes):
                for res in sample.results:
                    res: SubsamplingResult = res
                    method: meth.SubsamplingMethod = res.method
                    if methods == [] or method.matches_any_pattern(methods):
                        label: str = method.label
                        frac: float = method.fraction
                        error: float = res.mpCountError

                        if label not in result.keys():
                            result[label] = {frac: [error]}
                        elif frac not in result[label].keys():
                            result[label][frac] = [error]
                        else:
                            result[label][frac].append(error)
93 94 95 96 97 98 99

        for method in result.keys():
            methodRes: dict = result[method]
            for fraction in methodRes.keys():
                methodRes[fraction] = np.mean(methodRes[fraction])

        return result
100

Josef Brandt's avatar
Josef Brandt committed
101 102 103 104 105 106 107 108 109 110 111 112
    def _get_methods_for_fraction(self, dataset: dataset.DataSet, fraction: float) -> list:
        """
        :param fraction: The desired fraction to measure
        :return: list of measurement Objects that are applicable
        """
        particleContainer = dataset.particleContainer
        methods: list = [meth.RandomSampling(particleContainer, fraction),
                         meth.SizeBinFractioning(particleContainer, fraction)]

        boxCreator: gmeth.BoxSelectionCreator = gmeth.BoxSelectionCreator(dataset)
        methods += boxCreator.get_crossBoxSubsamplers_for_fraction(fraction)
        methods += boxCreator.get_spiralBoxSubsamplers_for_fraction(fraction)
113 114
        methods.append(cmeth.ChemometricSubsampling(particleContainer, fraction))
        # methods = [cmeth.ChemometricSubsampling(particleContainer, fraction)]
Josef Brandt's avatar
Josef Brandt committed
115 116 117 118
        return methods


class SampleResult(object):
119 120 121 122
    """
    An object the actually stores all generated results per sample and can update and report on them.
    """
    def __init__(self, filepath: str):
Josef Brandt's avatar
Josef Brandt committed
123
        super(SampleResult, self).__init__()
124
        self.filepath: str = filepath
Josef Brandt's avatar
Josef Brandt committed
125 126
        self.dataset: dataset.DataSet = None
        self.results: list = []
127
        self.attributes: list = []
128 129 130

    @property
    def sampleName(self) -> str:
Josef Brandt's avatar
Josef Brandt committed
131
        return get_name_from_directory(self.filepath)
132

Josef Brandt's avatar
Josef Brandt committed
133 134
    def load_dataset(self) -> None:
        self.dataset = dataset.loadData(self.filepath)
135
        assert self.dataset is not None
136

Josef Brandt's avatar
Josef Brandt committed
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    def update_result_with_method(self, method: meth.SubsamplingMethod, force: bool = False) -> None:
        """
        Updates result with the given method (contains desiredFraction already)
        :param method: The SubsamplingMethod Object
        :param force: Wether to force an update. If False, the result is not updated, if it is already present.
        :return:
        """

        if not self._result_is_already_present(method) or force:
            if force:
                self._remove_result_of_method(method)

            if self.dataset is None:
                self.load_dataset()

            method.particleContainer = self.dataset.particleContainer
            newResult: SubsamplingResult = SubsamplingResult(method)
            self.results.append(newResult)
            newResult.update()

157 158 159 160 161 162 163 164 165 166
    def set_attribute(self, newAttribute: str) -> None:
        """
        Adds a new attribute to the sample, if it does not contain the attribute already
        :param newAttribute:
        :return:
        """
        if not self.has_attribute(newAttribute):
            self.attributes.append(newAttribute)
            print(f'sample {self.filepath} has now attribute {newAttribute}')

167 168 169 170 171 172 173 174
    def has_any_attribute(self, listOfAttributes: list) -> bool:
        hasAttr: bool = False
        for attr in listOfAttributes:
            if self.has_attribute(attr):
                hasAttr = True
                break
        return hasAttr

175
    def has_attribute(self, attribute: str) -> bool:
176 177
        attributes: list = [attr.lower() for attr in self.attributes]
        return attribute.lower() in attributes
178

Josef Brandt's avatar
Josef Brandt committed
179 180 181 182 183 184 185
    def _remove_result_of_method(self, method: meth.SubsamplingMethod) -> None:
        """
        Removes the specified result from the list
        :param method:
        :return:
        """
        for result in self.results:
186
            if method.equals(result.method):
Josef Brandt's avatar
Josef Brandt committed
187 188 189 190 191 192 193 194 195 196
                self.results.remove(result)

    def _result_is_already_present(self, method: meth.SubsamplingMethod) -> bool:
        """
        Checks, if a result with the given method (method type AND measured fraction) is already present.
        :param method: The method object, specifying the subsampling method and the measured fraction
        :return:
        """
        isPresent: bool = False
        for result in self.results:
197
            if method.equals(result.method):
Josef Brandt's avatar
Josef Brandt committed
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
                isPresent = True
                break
        return isPresent


class SubsamplingResult(object):
    """
    Stores all interesting results from a subsampling experiment
    """
    def __init__(self, subsamplingMethod: meth.SubsamplingMethod):
        super(SubsamplingResult, self).__init__()
        self.method: meth.SubsamplingMethod = subsamplingMethod
        self.fraction = self.method.fraction
        self.origParticleCount: int = None
        self.subSampledParticleCount: int = None
        self.mpCountError: float = None
        self.mpCountErrorPerBin: tuple = None
215 216
        # TODO: UPDATE PATTERNS -> ARE THESE REASONABLE???
        self.mpPatterns = ['poly', 'rubber', 'pb', 'pr', 'pg', 'py', 'pv']
217

Josef Brandt's avatar
Josef Brandt committed
218 219 220 221 222 223 224 225 226 227 228
    def update(self) -> None:
        """
        Updates all results from the method.
        :return:
        """
        assert self.method.particleContainer is not None
        origParticles: list = self.method.particleContainer.particles
        self.origParticleCount = len(origParticles)
        subParticles: list = self.method.apply_subsampling_method()
        self.subSampledParticleCount = len(subParticles)
        fraction: float = self.method.fraction
229

Josef Brandt's avatar
Josef Brandt committed
230
        self.mpCountError = self._get_mp_count_error(origParticles, subParticles, fraction)
231
        # print(f'{self.origParticleCount} particles, thereof {self.subSampledParticleCount} measured, error: {self.mpCountError}')
Josef Brandt's avatar
Josef Brandt committed
232
        self.mpCountErrorPerBin = self._get_mp_count_error_per_bin(origParticles, subParticles, fraction)
233
        # print(f'method {self.method.label} updated, result is {self.mpCountError}')
234

Josef Brandt's avatar
Josef Brandt committed
235
    def _get_mp_count_error_per_bin(self, allParticles: list, subParticles: list, fractionMeasured: float) -> tuple:
236 237 238 239 240 241 242 243
        binSorter = ParticleBinSorter()
        allParticlesInBins = binSorter.sort_particles_into_bins(allParticles)
        subParticlesInBins = binSorter.sort_particles_into_bins(subParticles)
        mpCountErrorsPerBin = []
        for allParticleBin, subParticleBin in zip(allParticlesInBins, subParticlesInBins):
            mpCountErrorsPerBin.append(self._get_mp_count_error(allParticleBin, subParticleBin, fractionMeasured))
        return binSorter.bins, mpCountErrorsPerBin
        
Josef Brandt's avatar
Josef Brandt committed
244
    def _get_mp_count_error(self, allParticles: list, subParticles: list, fractionMeasured: float) -> float:
245 246 247 248 249 250 251 252
        numMPOrig = self._get_number_of_MP_particles(allParticles)
        numMPEstimate = self._get_number_of_MP_particles(subParticles) / fractionMeasured
        
        if numMPOrig != 0:
            mpCountError = self._get_error_from_values(numMPOrig, numMPEstimate)
        elif numMPEstimate == 0:
            mpCountError = 0
        else:
Josef Brandt's avatar
Josef Brandt committed
253
            raise Exception  # >0 particles in subsample, whereas none in entire sample. This cannot be!
254 255 256
            
        return mpCountError
    
Josef Brandt's avatar
Josef Brandt committed
257
    def _get_error_from_values(self, exact: float, estimate: float) -> float:
258
        assert(exact != 0)
259
        return abs(exact - estimate) / exact * 100
260
    
Josef Brandt's avatar
Josef Brandt committed
261
    def _get_number_of_MP_particles(self, particleList: list) -> int:
262 263 264
        numMPParticles = 0
        for particle in particleList:
            assignment = particle.getParticleAssignment()
265
            for pattern in self.mpPatterns:
266 267 268 269
                if assignment.lower().find(pattern) != -1:
                    numMPParticles += 1
                    break

270
        return numMPParticles