test_chemometricMethods.py 12.8 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 54 55 56 57 58 59
    def test_get_color_hash(self):
        for color in ['red', 'green', 'violet', 'blue', 'Blue']:
            for numDigits in [4, 6, 8]:
                hashNumber: int = abs(hash(color)) % (10**numDigits)
                hashArray: np.ndarray = self.extractor._get_color_hash(color, numDigits)
                for i in range(hashArray.shape[0]):
                    self.assertEqual(hashArray[i], int(str(hashNumber)[i]))
60 61 62 63


class TestChemometricSubsampling(unittest.TestCase):
    def setUp(self) -> None:
64 65 66
        self.particleContainer: ParticleContainer = ParticleContainer(None)
        self.numParticles: int = 5
        self.particleContainer.initializeParticles(self.numParticles)
67 68 69 70
        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)
71 72 73
        self.particleContainer.setParticleContours([contours[0] for _ in range(self.numParticles)])
        self.chemSubs: cmeth.ChemometricSubsampling = cmeth.ChemometricSubsampling(self.particleContainer,
                                                                                   desiredFraction=0.1)
74

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 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
    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_indices_from_clusterLabels(self):
    #     numClusters: int = 3
    #     numPointsPerCluster: int = 50
    #     numNoisePoints: int = 10
    #
    #     # the random_state=1 guarantees same outcome always
    #     centers: list = [i[0] for i in np.random.rand(numClusters, 1, 2)]
    #     points, labels = make_blobs(numClusters*numPointsPerCluster, centers=centers, cluster_std=0.3,
    #                                 shuffle=False, random_state=1)
    #     centerIndices: list = [int(round(numPointsPerCluster / 2 + (i*numPointsPerCluster))) for i in range(numClusters)]
    #
    #     noisePoints: np.ndarray = np.random.rand(numNoisePoints, 2)
    #     noiseLabels: np.ndarray = np.array([-1] * numNoisePoints)
    #     points = np.vstack((points, noisePoints))
    #     labels = np.hstack((labels, noiseLabels))
    #
    #     origFraction: float = self.chemSubs.fraction
    #     numIndicesTotal: float = round(len(labels)) * origFraction
    #     fractionPerCluster: float = origFraction * (numIndicesTotal - numNoisePoints) / numIndicesTotal
    #     pointsPerCluster: float = round(numPointsPerCluster * fractionPerCluster)
    #
    #     self.assertEqual(numIndicesTotal, numNoisePoints + numClusters * pointsPerCluster)
    #
    #     # Conversion from list to np.ndarray is to make the below indexing work.
    #     indices: np.ndarray = np.array(self.chemSubs._get_indices_from_clusterLabels(points, labels, np.array(centerIndices)))
    #     # Here we only check the correct number of indices, but not if the correct ones
    #     # (close to the center indices) were selected. However, all noise indices shall be there!
    #     # self.assertEqual(len(indices), round(len(labels) * self.chemSubs.fraction))
    #     # self.assertEqual(len(indices[indices < 100]), round(100 * fractionPerCluster))  # Cluster 0
    #     # self.assertEqual(len(indices[np.logical_and(indices >= 100, indices < 200)]), round(100 * fractionPerCluster))  # Cluster 1
    #     # self.assertEqual(len(indices[indices >= 200]), round(100 * fractionPerCluster))  # Cluster 2
    #     # self.assertEqual(len(indices[indices >= 300]), numNoisePoints)  # Noise Cluster

    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)
152

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 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
                    tooFewPoints = numPointsToMeasure < (numClusters + (1 if numNoisePoints > 0 else 0))

                    pointsFound: int = 0
                    roundingErrorFound: bool = False
                    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

                                # if pointsPerCluster[clusterIndex] != pointsExpected:
                                #     print('error')
                                # if not roundingErrorFound:
                                diff = abs(pointsPerCluster[clusterIndex] - pointsExpected)
                                if diff > 1:
                                    print('argh')
                                self.assertTrue(diff <= 1)
                                    # if diff != 0:
                                    #     roundingErrorFound = True
                                # else:
                                #     self.assertEqual(pointsPerCluster[clusterIndex], pointsExpected)

                            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):
212
    #     fname = r'C:\Users\xbrjos\Desktop\temp MP\190326_MCII_WWTP_SB_50_1\190326_MCII_WWTP_SB_50_1.pkl'
213 214
    #     # 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'
215 216
    #     dset: dataset.Dataset = dataset.loadData(fname)
    #     self.chemSubs.particleContainer = dset.particleContainer
217 218 219 220 221 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
    #     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()