graphs.py 16.7 KB
Newer Older
Josef Brandt's avatar
Josef Brandt committed
1 2
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
Josef Brandt's avatar
Josef Brandt committed
3
from matplotlib.ticker import ScalarFormatter, FixedLocator
Josef Brandt's avatar
Josef Brandt committed
4 5
from scipy import optimize
from mpl_toolkits.mplot3d import Axes3D
Josef Brandt's avatar
Josef Brandt committed
6

Josef Brandt's avatar
Josef Brandt committed
7
import numpy as np
Josef Brandt's avatar
Josef Brandt committed
8 9
from evaluation import TotalResults, get_number_of_MP_particles, is_MP_particle
from chemometrics.imageOperations import get_particle_patchiness
10
from helpers import get_filterDimensions_from_dataset, get_center_from_filter_dimensions, convert_length_to_pixels
Josef Brandt's avatar
Josef Brandt committed
11 12


Josef Brandt's avatar
Josef Brandt committed
13 14
def get_error_vs_frac_plot(totalResults: TotalResults, attributes: list = [], methods: list = [], partCounts: list = [],
                           standarddevs=True, fill=True, poissonRef=True) -> Figure:
Josef Brandt's avatar
Josef Brandt committed
15 16 17 18
    if len(attributes) == 0 and len(methods) != 0:
        attributes = [[]]*len(methods)
    elif len(methods) == 0 and len(attributes) != 0:
        methods = [[]]*len(attributes)
Josef Brandt's avatar
Josef Brandt committed
19 20
    if len(partCounts) == 0:
        patchiness = [[]]*len(attributes)
Josef Brandt's avatar
Josef Brandt committed
21

Josef Brandt's avatar
Josef Brandt committed
22 23 24
    assert len(attributes) == len(methods)
    numRows: int = 1
    numCols: int = 1
Josef Brandt's avatar
Josef Brandt committed
25

Josef Brandt's avatar
Josef Brandt committed
26 27 28 29 30 31 32 33
    if len(attributes) == 0:
        attributes = methods = [[]]
    elif len(attributes) <= 2:
        numCols = len(attributes)
    else:
        numRows = 2
        numCols = np.ceil(len(attributes)/numRows)

Josef Brandt's avatar
Josef Brandt committed
34 35
    fig: Figure = plt.figure(figsize=(14, 3.5 * numRows))

Josef Brandt's avatar
Josef Brandt committed
36
    index = 0
Josef Brandt's avatar
Josef Brandt committed
37
    for attrs, meths, pcounts in zip(attributes, methods, partCounts):
Josef Brandt's avatar
Josef Brandt committed
38
        ax = fig.add_subplot(numRows, numCols, index + 1)
Josef Brandt's avatar
Josef Brandt committed
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
        if pcounts != []:
            stats, errorPerFraction = totalResults.get_error_vs_fraction_data(attributes=attrs, methods=meths,
                                                                              partCount=pcounts)
        else:
            stats, errorPerFraction = totalResults.get_error_vs_fraction_data(attributes=attrs, methods=meths)
        numSamples = stats['numSamples']
        meanParticleCount = stats['meanParticleCount']
        meanMPFrac = stats['meanMPFrac']

        if poissonRef:
            firstSample: str = list(errorPerFraction.keys())[0]
            fractions: list = list(errorPerFraction[firstSample].keys())
            meansCounts: np.ndarray = np.array([frac * meanParticleCount * meanMPFrac/100 for frac in fractions])
            stdevs: np.ndarray = 1 / np.sqrt(meansCounts)  # mean = varianz = stdev**2 in Poisson Distribution
            means = stdevs**2

            #Conversions to %
            means *= 100
            stdevs *= 100
            fractions = [frac*100 for frac in fractions]

            if not standarddevs:
                ax.plot(fractions, means, label='Poisson', marker='s', alpha=0.3)
            else:
                line = ax.errorbar(fractions, means, stdevs, label='Poisson', marker='s', capsize=5, alpha=0.3)
                if fill:
                    color = line[0].get_color()
                    ax.fill_between(fractions, means-stdevs, means+stdevs, alpha=0.1, facecolor=color)
                    # print('errorbars:', means-stdevs, means+stdevs)
Josef Brandt's avatar
Josef Brandt committed
68 69 70 71

        for methodLabel in errorPerFraction.keys():
            errorDict: dict = errorPerFraction[methodLabel]
            fractions: list = list(errorDict.keys())
Josef Brandt's avatar
Josef Brandt committed
72 73
            errors: np.ndarray = np.array([errorDict[fraction][0] for fraction in fractions])
            stdevs: np.ndarray = np.array([errorDict[fraction][1] for fraction in fractions])
Josef Brandt's avatar
Josef Brandt committed
74

Josef Brandt's avatar
Josef Brandt committed
75 76 77
            fractions = [i * 100 for i in fractions]  # convert to % for plotting

            alphascale: float = 1 if methodLabel.find('Random Subsa') == -1 else 0.3
Josef Brandt's avatar
Josef Brandt committed
78

Josef Brandt's avatar
Josef Brandt committed
79
            if not standarddevs:
Josef Brandt's avatar
Josef Brandt committed
80
                ax.plot(fractions, errors, label=methodLabel, marker='s')
Josef Brandt's avatar
Josef Brandt committed
81
            else:
Josef Brandt's avatar
Josef Brandt committed
82
                line = ax.errorbar(fractions, errors, stdevs, label=methodLabel, marker='s', capsize=5, alpha=alphascale)
Josef Brandt's avatar
Josef Brandt committed
83 84
                if fill:
                    color = line[0].get_color()
Josef Brandt's avatar
Josef Brandt committed
85 86
                    ax.fill_between(fractions, errors-stdevs, errors+stdevs, alpha=0.2*alphascale, facecolor=color)

Josef Brandt's avatar
Josef Brandt committed
87 88
        title: str = ''
        if len(attrs) > 0:
Josef Brandt's avatar
Josef Brandt committed
89 90 91
            for i in range(len(attrs)):
                if attrs[i] == 'slush':
                    attrs[i] = 'sludge'
Josef Brandt's avatar
Josef Brandt committed
92
            title = ', '.join(attr for attr in attrs)
Josef Brandt's avatar
Josef Brandt committed
93 94 95 96 97 98

        elif pcounts != []:
            title += f'{pcounts[0]} <= num. Particles < {pcounts[1]}'

        meanNumMP: int = int(round(meanParticleCount * meanMPFrac/100, 0))
        title += f' ({numSamples} filters)\nAverage: {meanParticleCount} particles, {meanMPFrac} % MP, {meanNumMP} MP particles'
99

Josef Brandt's avatar
Josef Brandt committed
100
        ax.set_title(title, fontSize=13)
Josef Brandt's avatar
Josef Brandt committed
101
        ax.set_xscale('log')
Josef Brandt's avatar
Josef Brandt committed
102 103 104 105 106
        ax.xaxis.set_major_formatter(ScalarFormatter())
        # ax.xaxis.set_major_locator(FixedLocator([0.02, 0.05, 0.1, 0.2, 0.5, 1.0]))
        ax.xaxis.set_major_locator(FixedLocator([2, 5, 10, 20, 50, 100]))

        ax.set_xlabel('measured fraction (%)', fontsize=12)
Josef Brandt's avatar
Josef Brandt committed
107
        ax.set_ylabel('subsampling-error (%)', fontsize=12)
Josef Brandt's avatar
Josef Brandt committed
108
        minX, maxX = 0.9 * min(fractions), 105
109 110
        ax.hlines([20, 40, 60, 80], minX, maxX, colors='gray', alpha=0.5)
        ax.set_xlim([minX, maxX])
Josef Brandt's avatar
Josef Brandt committed
111 112 113 114
        ax.set_ylim([0, 100])
        ax.legend()

        index += 1
Josef Brandt's avatar
Josef Brandt committed
115 116
        
    fig.tight_layout()
Josef Brandt's avatar
Josef Brandt committed
117 118 119
    return fig


120
def get_distance_hist_plots(totalResults: TotalResults, attributes: list = []) -> Figure:
Josef Brandt's avatar
Josef Brandt committed
121
    fig: Figure = plt.figure(figsize=(7, 5))
122 123 124 125 126 127 128 129 130 131
    numRows: int = 1
    numCols: int = 1
    if len(attributes) == 0:
        attributes = [[]]
    elif len(attributes) <= 2:
        numCols = len(attributes)
    else:
        numRows = 2
        numCols = np.ceil(len(attributes) / numRows)

Josef Brandt's avatar
Josef Brandt committed
132 133
    onlyMP: bool = True
    ax = fig.add_subplot()
134
    for index, attrs in enumerate(attributes):
Josef Brandt's avatar
Josef Brandt committed
135
        # ax = fig.add_subplot(numRows, numCols, index + 1)
Josef Brandt's avatar
Josef Brandt committed
136
        allParticles: list = []
137
        densities: list = []
Josef Brandt's avatar
Josef Brandt committed
138 139
        particleCounts: list = []
        pathinesses: list = []
140 141 142 143 144 145
        for sampleRes in totalResults.sampleResults:
            if sampleRes.has_any_attribute(attrs):
                if sampleRes.dataset is None:
                    sampleRes.load_dataset()

                dset = sampleRes.dataset
Josef Brandt's avatar
Josef Brandt committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
                patchiness: float = get_particle_patchiness(dset, onlyMP=onlyMP)
                pathinesses.append(patchiness)
                if onlyMP:
                    particleCount: int = 0
                    for particle in dset.particleContainer.particles:
                        if is_MP_particle(particle):
                            particleCount += 1
                    particleCounts.append(particleCount)
                else:
                    particleCounts.append(len(dset.particleContainer.particles))

                # for particle in dset.particleContainer.particles:
                #     allParticles.append(particle)
                #
                # offset, diameter, [width, height] = get_filterDimensions_from_dataset(dset)
                # center = get_center_from_filter_dimensions(offset, diameter)
                # center[0] = convert_length_to_pixels(dset, center[0])
                # center[1] = convert_length_to_pixels(dset, center[1])

                # histdata = get_distance_point_histogramdata(dset.particleContainer.particles, center)
                # densities.append(histdata[1])
167 168
                # ax.plot(histdata[0], histdata[1])

Josef Brandt's avatar
Josef Brandt committed
169 170 171 172 173 174
        for i in range(len(attrs)):
            if attrs[i] == 'slush':
                attrs[i] = 'sludge'
        ax.scatter(particleCounts, pathinesses, label=', '.join(attr for attr in attrs))

        # numSamples = len(densities)
Josef Brandt's avatar
Josef Brandt committed
175
        # partCounts: list = [len(i) for i in allParticles]
Josef Brandt's avatar
Josef Brandt committed
176
        # meanParticleCount: float = round(len(allParticles) / numSamples)
Josef Brandt's avatar
Josef Brandt committed
177 178 179 180 181 182
        # meanParticleCount: float = round(np.mean(partCounts))
        # stdParticleCount: float = round(np.std(partCounts))

        # mpFracs: list = [get_number_of_MP_particles(i)/len(i) for i in allParticles]
        # meanMPFrac: float = round(np.mean(mpFracs) * 100, 1)
        # stdMPFrac: float = round(np.std(mpFracs) * 100, 1)
Josef Brandt's avatar
Josef Brandt committed
183 184 185 186 187 188 189 190
        # numMPParticles: float = get_number_of_MP_particles(allParticles)
        # meanMPFrac: float = round(numMPParticles / len(allParticles) * 100, 1)
        # meanPatchiness: float = round(np.mean(pathinesses), 2)
        # title: str = ''
        # if len(attrs) > 0:
        #     title = ', '.join(attr for attr in attrs)
        #     title += f'\n({numSamples} filters, avg. {meanParticleCount} particles, {meanMPFrac} % MP,'
        #     title += f'\navg. Particle Patchiness {meanPatchiness})'
191

Josef Brandt's avatar
Josef Brandt committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
        # ax.set_title(title, fontSize=13)
        # densities: np.ndarray = np.mean(np.array(densities), axis=0)
        # densities /= densities.max()
        # distances = np.array(histdata[0], dtype=np.float) * dset.pixelscale_df
        # ax.plot(distances / 1000, densities)
        # ax.set_xlabel('distance from filter center (mm)', fontsize=12)
        # ax.set_xlim([0, 6])
        # ax.set_ylabel('normalized particle density', fontsize=12)
        # ax.set_ylim([0.0, 1.05])

    ax.legend(fontsize=15)

    ax.set_xscale('log')
    if not onlyMP:
        ax.set_xticks([1000, 5000, 10000, 50000, 100000])
        ax.set_xlabel('Particle Count', fontsize=15)
    else:
        ax.set_xticks([10, 50, 100, 500])
        ax.set_xlabel('MP Particle Count', fontsize=15)
211

Josef Brandt's avatar
Josef Brandt committed
212 213 214 215 216 217
    ax.xaxis.set_major_formatter(ScalarFormatter())
    ax.set_ylabel('Patchiness', fontsize=15)
    for tick in ax.xaxis.get_major_ticks():
        tick.label.set_fontsize(15)
    for tick in ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(15)
Josef Brandt's avatar
Josef Brandt committed
218
    fig.tight_layout()
219 220 221
    return fig


Josef Brandt's avatar
Josef Brandt committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 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 345 346 347 348 349
def get_error_vs_mpfrac_plot(totalResults: TotalResults, attributes: list = []) -> Figure:
    def quadratic_fit(x, a, b, c):
        return a*x**2 + b*x + c

    fig: Figure = plt.figure(figsize=(15, 5))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    dataWithFractions: dict = {}
    dataWithNumbers: dict = {}
    
    for index, attrs in enumerate(attributes):
        for sampleRes in totalResults.sampleResults:
            if sampleRes.has_any_attribute(attrs):
                if sampleRes.dataset is None:
                    sampleRes.load_dataset()

                dset = sampleRes.dataset
                particles: list = dset.particleContainer.particles
                totalParticleCount: int = len(particles)
                numMPParticles: float = get_number_of_MP_particles(particles)
                mpfrac: float = numMPParticles / totalParticleCount * 100

                fracsMeasured: np.ndarray = np.unique([result.method.fraction for result in sampleRes.results])
                fracsToPlot: dict = {0.03: 0.03,
                                     0.04: 0.03,
                                     0.05: 0.03,
                                     0.06: 0.1,
                                     0.1: 0.1,
                                     0.2: 0.1,
                                     0.25: 0.1,
                                     0.3: 0.5,
                                     0.5: 0.5,
                                     0.7: 0.8,
                                     0.9: 0.8
                                     }
                numParticlesMeasured: list = [1000, 2500, 5000]
                usedSamples: list = []
                for particlesMeasured in numParticlesMeasured:
                    if particlesMeasured <= totalParticleCount:
                        fracMeasured: float = particlesMeasured/totalParticleCount
                        indexOfFracToEvaluate = np.argmin(np.abs(fracsMeasured - fracMeasured))
                        fracToEvaluate: float = fracsMeasured[indexOfFracToEvaluate]

                        allErrorsOfThisFrac: list = []
                        for result in sampleRes.results:
                            if result.method.label.find('Random Subsampling') != -1 and result.method.fraction == fracToEvaluate:
                                allErrorsOfThisFrac.append(result.mpCountError)

                        if mpfrac != 0.0:
                            if particlesMeasured not in dataWithNumbers:
                                dataWithNumbers[particlesMeasured] = [(mpfrac, np.mean(allErrorsOfThisFrac))]
                            else:
                                dataWithNumbers[particlesMeasured].append((mpfrac, np.mean(allErrorsOfThisFrac)))

                            fracToEvaluate = fracsToPlot[fracToEvaluate]
                            if fracToEvaluate not in dataWithFractions.keys():
                                dataWithFractions[fracToEvaluate] = [(mpfrac, np.mean(allErrorsOfThisFrac))]
                            else:
                                dataWithFractions[fracToEvaluate].append((mpfrac, np.mean(allErrorsOfThisFrac)))

                # fracsToProcess: list = [0.03, 0.1, 0.5, 0.8]
                # for fracToEvaluate in fracsToProcess:
                #     allErrorsOfThisFrac: list = []
                #     for result in sampleRes.results:
                #         if result.method.label.find('Random Subsampling') != -1 and result.method.fraction == fracToEvaluate:
                #             allErrorsOfThisFrac.append(result.mpCountError)
                #
                #     if mpfrac != 0.0:
                #         if fracToEvaluate not in dataWithFractions.keys():
                #             dataWithFractions[fracToEvaluate] = [(mpfrac, np.mean(allErrorsOfThisFrac))]
                #         else:
                #             dataWithFractions[fracToEvaluate].append((mpfrac, np.mean(allErrorsOfThisFrac)))

    for frac in sorted(dataWithFractions.keys()):
        mpfracs: np.ndarray = np.array([i[0] for i in dataWithFractions[frac]])
        errors: np.ndarray = np.array([i[1] for i in dataWithFractions[frac]])
        ax1.scatter(mpfracs, errors, marker='o', label=f'measured Fraction: {frac}')

        if mpfracs.shape[0] <= 2 or not np.asarray_chkfinite(errors.any()):
            ax1.plot(np.sort(mpfracs), errors)
        else:
            x_for_fit = np.log10(mpfracs)
            try:
                params, _ = optimize.curve_fit(quadratic_fit, x_for_fit, errors)
            except ValueError:
                print('break')
                continue
            ax1.plot(np.sort(mpfracs), quadratic_fit(np.sort(x_for_fit), params[0], params[1], params[2]))

    for numParticles in sorted(dataWithNumbers.keys()):
        mpfracs: np.ndarray = np.array([i[0] for i in dataWithNumbers[numParticles]])
        errors: np.ndarray = np.array([i[1] for i in dataWithNumbers[numParticles]])
        ax2.scatter(mpfracs, errors, marker='o', label=f'measured {numParticles} particles')

        if mpfracs.shape[0] > 2:
            x_for_fit = np.log10(mpfracs)
            params, _ = optimize.curve_fit(quadratic_fit, x_for_fit, errors)
            ax2.plot(np.sort(mpfracs), quadratic_fit(np.sort(x_for_fit), params[0], params[1], params[2]))

    for axis in [ax1, ax2]:
        axis.set_xlabel('microplastic Fraction (%)', fontsize=15)
        axis.set_xlim([0.08, 15])
        axis.set_xscale('log')
        axis.set_ylabel('subsampling error (%)', fontsize=15)
        axis.set_ylim([0, 120])
        axis.xaxis.set_major_formatter(ScalarFormatter())
        axis.hlines([20], 0.08, 15, colors='gray', alpha=0.5)
        axis.text(2.5, 22, 'recommended limit', fontsize=14, alpha=0.5)

        for tick in axis.xaxis.get_major_ticks():
            tick.label.set_fontsize(15)
        for tick in axis.yaxis.get_major_ticks():
            tick.label.set_fontsize(15)

        handles, labels = axis.get_legend_handles_labels()
        by_label = dict(zip(labels, handles))
        axis.legend(by_label.values(), by_label.keys(), fontsize=15)

    ax1.set_title('By Fraction', fontsize=17)
    ax2.set_title('By Particle Count', fontsize=17)

    fig.tight_layout()
    return fig




350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
def get_distance_point_histogramdata(particles: list, center: np.ndarray) -> tuple:
    """
    :param particles: list of Particles
    :param center: np.array([x, y]) of center point, in px
    :return histogramdata: tuple: (center bin dist ,  particle count)
    """
    def get_area_of_circle_ring(innerRadius: float, outerRadius: float) -> float:
        area: float = np.pi * (outerRadius + innerRadius) * (outerRadius - innerRadius)
        return area

    maxUpperLimit: float = 1E4
    numBins: int = 11
    bins: np.ndarray = np.linspace(0, maxUpperLimit, numBins, endpoint=True)

    particleCenters: list = []
    for particle in particles:
        particleCenters.append([np.mean(particle.contour[:, 0, 0]), np.mean(particle.contour[:, 0, 1])])

    distancesToPoints: np.ndarray = np.linalg.norm(particleCenters - center, axis=1)
    data, binMaxima = np.histogram(distancesToPoints, bins)
    densities: np.ndarray = np.zeros_like(data, dtype=np.float)
    for i in range(len(data)):
        densities[i] = float(data[i]) / get_area_of_circle_ring(binMaxima[i], binMaxima[i+1])

    binCenters: list = [np.mean([binMaxima[i], binMaxima[i+1]]) for i in range(len(binMaxima)-1)]
    return binCenters, densities
Josef Brandt's avatar
Josef Brandt committed
376