test_chemometricMethods.py 10.2 KB
Newer Older
1 2 3 4 5
import unittest
import cv2
import numpy as np
import sys
import matplotlib.pyplot as plt
6 7 8
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import DBSCAN
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

sys.path.append("C://Users//xbrjos//Desktop//Python")
from gepard.analysis import particleAndMeasurement as pm
from gepard.analysis.particleContainer import ParticleContainer
from gepard import dataset

import chemometricMethods as cmeth


class TestFeatureExtractor(unittest.TestCase):
    def setUp(self) -> None:
        self.extractor: cmeth.FeatureExtractor = cmeth.FeatureExtractor(None)

    def test_get_contour_moments(self):
        imgs = []
        imgA: np.ndarray = np.zeros((200, 200), dtype=np.uint8)
        cv2.putText(imgA, 'A', (25, 175), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=7, color=1, thickness=5)
        imgs.append(imgA.copy())

        imgA_translated: np.ndarray = np.zeros((200, 200), dtype=np.uint8)
        cv2.putText(imgA_translated, 'A', (10, 180), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=7, color=1, thickness=5)
        imgs.append(imgA_translated)
        imgs.append(cv2.rotate(imgA, cv2.ROTATE_90_CLOCKWISE))
        imgs.append(cv2.rotate(imgA, cv2.ROTATE_180))
        imgs.append(cv2.resize(imgA, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR))
        imgs.append(cv2.resize(imgA, None, fx=1.5, fy=1.5, interpolation=cv2.INTER_LINEAR))

        moments: np.ndarray = np.zeros((7, len(imgs)))  # we prepare an empty array for 7 hu moments per image
        for i, img in enumerate(imgs):
            contours, hierarchy = cv2.findContours(img, 1, 2)
            particle: pm.Particle = pm.Particle()
            particle.contour = contours[0]
            self.extractor.particle = particle
            hu: np.ndarray = self.extractor._get_log_hu_moments()
            moments[:, i] = hu

        # The first six hu moments are supposed to be invariant to scale, rotation and translation
        # Small errors can occur, as the test image is of low resolution...
        for i in range(6):
            diff: np.ndarray = moments[i, :] - np.mean(moments[i, :])
            self.assertFalse(np.any(diff > 0.1))

53
    def test_get_color_hash(self):
Josef Brandt's avatar
Josef Brandt committed
54
        for color in ['red', 'green', 'violet', 'blue', 'Blue', 'non-determinable', None]:
55
            for numDigits in [4, 6, 8]:
Josef Brandt's avatar
Josef Brandt committed
56
                hashNumber: int = abs(hash(color))
57
                hashArray: np.ndarray = self.extractor._get_color_hash(color, numDigits)
Josef Brandt's avatar
Josef Brandt committed
58 59
                self.assertEqual(len(hashArray), numDigits)
                for i in range(numDigits):
60
                    self.assertEqual(hashArray[i], int(str(hashNumber)[i]))
61 62 63 64


class TestChemometricSubsampling(unittest.TestCase):
    def setUp(self) -> None:
65 66 67
        self.particleContainer: ParticleContainer = ParticleContainer(None)
        self.numParticles: int = 5
        self.particleContainer.initializeParticles(self.numParticles)
68 69 70 71
        img: np.ndarray = np.zeros((20, 20), dtype=np.uint8)
        cv2.putText(img, 'A', (2, 2), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=1, color=1, thickness=2)
        contours, hierarchy = cv2.findContours(img, 1, 2)
72 73 74
        self.particleContainer.setParticleContours([contours[0] for _ in range(self.numParticles)])
        self.chemSubs: cmeth.ChemometricSubsampling = cmeth.ChemometricSubsampling(self.particleContainer,
                                                                                   desiredFraction=0.1)
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
    def test_get_particle_featurematrix(self):
        features: np.ndarray = self.chemSubs._get_particle_featurematrix()
        self.assertEqual(features.shape, (11, self.numParticles))
        for i in range(6):
            diff: np.ndarray = features[i, :] - np.mean(features[i, :])
            self.assertFalse(np.any(diff > 0.1))

    def test_get_numPoints_per_cluster(self):
        def get_orig_points_per_cluster(index):
            return (index+1)*50

        # numPointsPerCluster: int = 50
        for frac in [0.01, 0.1, 0.5, 0.9]:
            self.chemSubs.fraction = frac
            for numClusters in [1, 5, 10]:
                for numNoisePoints in [0, 10, 15]:
                    labels: list = []
                    for clusterIndex in range(numClusters):
                        # for _ in range(numPointsPerCluster):
                        for _ in range(get_orig_points_per_cluster(clusterIndex)):
                            labels.append(clusterIndex)
                    for _ in range(numNoisePoints):
                        labels.append(-1)

                    labels: np.ndarray = np.array(labels)
                    numTotal: int = len(labels)
                    origFrac: float = self.chemSubs.fraction

                    noiseAmpFactor = np.clip(5, 0, 1/frac)
                    pointsPerCluster: dict = self.chemSubs._get_numPoints_per_cluster(labels,
                                                                                      noiseAmpFactor=noiseAmpFactor)
                    numPointsToMeasure = round(numTotal*origFrac)
                    if numPointsToMeasure == 0:
                        numPointsToMeasure = 1

                    self.assertTrue(abs(sum(list(pointsPerCluster.values())) - numPointsToMeasure) <= 1)

                    if numNoisePoints == 0:
                        fractionPerCluster: float = frac
                    else:
                        # fractionPerCluster: float = numPointsToMeasure / (numClusters*numPointsPerCluster +
                        #                                                   numNoisePoints*noiseAmpFactor)
                        fractionPerCluster: float = numPointsToMeasure / (len(labels) - numNoisePoints +
                                                                          numNoisePoints * noiseAmpFactor)
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
                    tooFewPoints = numPointsToMeasure < (numClusters + (1 if numNoisePoints > 0 else 0))

                    pointsFound: int = 0
                    for clusterIndex in pointsPerCluster.keys():
                        if clusterIndex > -1:
                            if not tooFewPoints:
                                pointsExpected = round(fractionPerCluster * get_orig_points_per_cluster(clusterIndex))
                                if pointsExpected == 0:
                                    pointsExpected = 1

                                diff = abs(pointsPerCluster[clusterIndex] - pointsExpected)
                                self.assertTrue(diff <= 1)
                            else:
                                if pointsFound < numPointsToMeasure:
                                    self.assertEqual(pointsPerCluster[clusterIndex], 1)
                                else:
                                    self.assertEqual(pointsPerCluster[clusterIndex], 0)

                            pointsFound += pointsPerCluster[clusterIndex]

                    if numNoisePoints > 0:
                        self.assertTrue(abs(pointsPerCluster[-1] - (numPointsToMeasure - pointsFound)) <= 1)

    def test_get_n_points_closest_to_center(self):
        points: np.ndarray = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
        refPoint: np.ndarray = np.array([0, 0])
        closestPoints: list = cmeth.get_n_points_closest_to_point(points, 3, refPoint)
        self.assertEqual(len(closestPoints), 3)
        self.assertTrue(0 in closestPoints)
        self.assertTrue(1 in closestPoints)
        self.assertTrue(2 in closestPoints)

        refPoint = np.array([2, 2])
        closestPoints = cmeth.get_n_points_closest_to_point(points, 3, refPoint)
        self.assertEqual(len(closestPoints), 3)
        self.assertTrue(1 in closestPoints)
        self.assertTrue(2 in closestPoints)
        self.assertTrue(3 in closestPoints)

        refPoint = np.array([2, 0.5])
        closestPoints = cmeth.get_n_points_closest_to_point(points, 2, refPoint)
        self.assertEqual(len(closestPoints), 2)
        self.assertTrue(2 in closestPoints)
        self.assertTrue(3 in closestPoints)



    # def test_clustering(self):
169
    #     fname = r'C:\Users\xbrjos\Desktop\temp MP\190326_MCII_WWTP_SB_50_1\190326_MCII_WWTP_SB_50_1.pkl'
170 171
    #     # fname = r'C:\Users\xbrjos\Desktop\temp MP\190313_Soil_5_A_50_5_1_50_1\190313_Soil_5_A_50_5_1_50_1.pkl'
    #     # fname = r'C:\Users\xbrjos\Desktop\temp MP\190201_BSB_Stroomi_ds2_R1_R2_50\190201_BSB_Stroomi_ds2_R1_R2_50.pkl'
172 173
    #     dset: dataset.Dataset = dataset.loadData(fname)
    #     self.chemSubs.particleContainer = dset.particleContainer
174 175 176 177 178 179 180 181 182 183 184 185 186 187 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
    #     features: np.ndarray = self.chemSubs._get_particle_featurematrix()
    #     princComps: np.ndarray = cmeth.get_pca(features)
    #
    #     X = StandardScaler().fit_transform(princComps)
    #
    #     #############################################################################
    #     # Compute DBSCAN
    #     db = DBSCAN(eps=0.1, min_samples=10).fit(X)
    #
    #     core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
    #     core_samples_mask[db.core_sample_indices_] = True
    #     labels = db.labels_
    #
    #     # Number of clusters in labels, ignoring noise if present.
    #     n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
    #     n_noise_ = list(labels).count(-1)
    #
    #     print('Estimated number of clusters: %d' % n_clusters_)
    #     print('Estimated number of noise points: %d' % n_noise_)
    #
    #     # Black removed and is used for noise instead.
    #     unique_labels = set(labels)
    #     colors = [plt.cm.Spectral(each)
    #               for each in np.linspace(0, 1, len(unique_labels))]
    #     for k, col in zip(unique_labels, colors):
    #         if k == -1:
    #             # Black used for noise.
    #             col = [0, 0, 0, 1]
    #
    #         class_member_mask = (labels == k)
    #
    #         xy = X[class_member_mask & core_samples_mask]
    #         plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
    #                  markeredgecolor='k', markersize=14)
    #
    #         xy = X[class_member_mask & ~core_samples_mask]
    #         plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
    #                  markeredgecolor='k', markersize=6)
    #
    #     plt.title('Estimated number of clusters: %d' % n_clusters_)
    #     plt.show()