File: test_hierarchical.py

package info (click to toggle)
python-cluster 1.4.1.post3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 412 kB
  • sloc: python: 812; makefile: 146; sh: 4
file content (272 lines) | stat: -rw-r--r-- 8,900 bytes parent folder | download
1
2
3
4
5
6
7
8
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
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
212
213
214
215
216
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#
# This is part of "python-cluster". A library to group similar items together.
# Copyright (C) 2006    Michel Albert
#
# This library is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
# This library 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 Lesser General Public License for more
# details.
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

"""
Tests for hierarchical clustering.

.. note::

    Even though the results are lists, the order of items in the resulting
    clusters is non-deterministic. This should be taken into consideration when
    writing "expected" values!
"""

from difflib import SequenceMatcher
from math import sqrt
from sys import hexversion
import unittest

from cluster import HierarchicalClustering


class Py23TestCase(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        super(Py23TestCase, self).__init__(*args, **kwargs)
        if hexversion < 0x030000f0:
            self.assertCItemsEqual = self.assertItemsEqual
        else:
            self.assertCItemsEqual = self.assertCountEqual


class HClusterSmallListTestCase(Py23TestCase):
    """
    Test for Bug #1516204
    """

    def testClusterLen1(self):
        """
        Testing if hierarchical clustering a set of length 1 returns a set of
        length 1
        """
        cl = HierarchicalClustering([876], lambda x, y: abs(x - y))
        self.assertCItemsEqual([876], cl.getlevel(40))

    def testClusterLen0(self):
        """
        Testing if hierarchical clustering an empty list returns an empty list
        """
        cl = HierarchicalClustering([], lambda x, y: abs(x - y))
        self.assertEqual([], cl.getlevel(40))


class HClusterIntegerTestCase(Py23TestCase):

    def setUp(self):
        self.__data = [791, 956, 676, 124, 564, 84, 24, 365, 594, 940, 398,
                       971, 131, 365, 542, 336, 518, 835, 134, 391]

    def testSingleLinkage(self):
        "Basic Hierarchical Clustering test with integers"
        cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y))
        result = cl.getlevel(40)

        # sort the values to make the tests less prone to algorithm changes
        result = [sorted(_) for _ in result]
        self.assertCItemsEqual([
            [24],
            [336, 365, 365, 391, 398],
            [518, 542, 564, 594],
            [676],
            [791],
            [835],
            [84, 124, 131, 134],
            [940, 956, 971],
        ], result)

    def testCompleteLinkage(self):
        "Basic Hierarchical Clustering test with integers"
        cl = HierarchicalClustering(self.__data,
                                    lambda x, y: abs(x - y),
                                    linkage='complete')
        result = cl.getlevel(40)

        # sort the values to make the tests less prone to algorithm changes
        result = sorted([sorted(_) for _ in result])

        expected = [
            [24],
            [84],
            [124, 131, 134],
            [336, 365, 365],
            [391, 398],
            [518],
            [542, 564],
            [594],
            [676],
            [791],
            [835],
            [940, 956, 971],
        ]
        self.assertEqual(result, expected)

    def testUCLUS(self):
        "Basic Hierarchical Clustering test with integers"
        cl = HierarchicalClustering(self.__data,
                                    lambda x, y: abs(x - y),
                                    linkage='uclus')
        expected = [
            [24],
            [84],
            [124, 131, 134],
            [336, 365, 365, 391, 398],
            [518, 542, 564],
            [594],
            [676],
            [791],
            [835],
            [940, 956, 971],
        ]
        result = sorted([sorted(_) for _ in cl.getlevel(40)])
        self.assertEqual(result, expected)

    def testAverageLinkage(self):
        cl = HierarchicalClustering(self.__data,
                                    lambda x, y: abs(x - y),
                                    linkage='average')
        # TODO: The current test-data does not really trigger a difference
        # between UCLUS and "average" linkage.
        expected = [
            [24],
            [84],
            [124, 131, 134],
            [336, 365, 365, 391, 398],
            [518, 542, 564],
            [594],
            [676],
            [791],
            [835],
            [940, 956, 971],
        ]
        result = sorted([sorted(_) for _ in cl.getlevel(40)])
        self.assertEqual(result, expected)

    def testUnmodifiedData(self):
        cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y))
        new_data = []
        [new_data.extend(_) for _ in cl.getlevel(40)]
        self.assertEqual(sorted(new_data), sorted(self.__data))

    def testMultiprocessing(self):
        cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y),
                                    num_processes=4)
        new_data = []
        [new_data.extend(_) for _ in cl.getlevel(40)]
        self.assertEqual(sorted(new_data), sorted(self.__data))


class HClusterStringTestCase(Py23TestCase):

    def sim(self, x, y):
        sm = SequenceMatcher(lambda x: x in ". -", x, y)
        return 1 - sm.ratio()

    def setUp(self):
        self.__data = ("Lorem ipsum dolor sit amet consectetuer adipiscing "
                       "elit Ut elit Phasellus consequat ultricies mi Sed "
                       "congue leo at neque Nullam").split()

    def testDataTypes(self):
        "Test for bug #?"
        cl = HierarchicalClustering(self.__data, self.sim)
        for item in cl.getlevel(0.5):
            self.assertEqual(
                type(item), type([]),
                "Every item should be a list!")

    def testCluster(self):
        "Basic Hierachical clustering test with strings"
        self.skipTest('These values lead to non-deterministic results. '
                      'This makes it untestable!')
        cl = HierarchicalClustering(self.__data, self.sim)
        self.assertEqual([
            ['ultricies'],
            ['Sed'],
            ['Phasellus'],
            ['mi'],
            ['Nullam'],
            ['sit', 'elit', 'elit', 'Ut', 'amet', 'at'],
            ['leo', 'Lorem', 'dolor'],
            ['congue', 'neque', 'consectetuer', 'consequat'],
            ['adipiscing'],
            ['ipsum'],
        ], cl.getlevel(0.5))

    def testUnmodifiedData(self):
        cl = HierarchicalClustering(self.__data, self.sim)
        new_data = []
        [new_data.extend(_) for _ in cl.getlevel(0.5)]
        self.assertEqual(sorted(new_data), sorted(self.__data))


class HClusterTuplesTestCase(Py23TestCase):
    '''
    Test case to cover the case where the data contains tuple-items

    See Github issue #20
    '''

    def testSingleLinkage(self):
        "Basic Hierarchical Clustering test with integers"

        def euclidian_distance(a, b):
            return sqrt(sum([pow(z[0] - z[1], 2) for z in zip(a, b)]))

        self.__data = [(1, 1), (1, 2), (1, 3)]
        cl = HierarchicalClustering(self.__data, euclidian_distance)
        result = cl.getlevel(40)
        self.assertIsNotNone(result)

class Issue28TestCase(Py23TestCase):
    '''
    Test case to cover the case where the data consist
    of dictionary keys, and the distance function executes 
    on the values these keys are associated with in the
    dictionary, rather than the keys themselves.

    Behaviour for this test case differs between Python2.7
    and Python3.5: on 2.7 the test behaves as expected, 

    See Github issue #28.
    '''

    def testIssue28(self):
        "Issue28 (Hierarchical Clustering)"

        points1D = {
            'p4' : 5, 'p2' : 6, 'p7' : 10,
            'p9' : 120, 'p10' : 121, 'p11' : 119,
        }

        distance_func = lambda a,b : abs(points1D[a]-points1D[b])
        cl = HierarchicalClustering(list(points1D.keys()), distance_func)
        result = cl.getlevel(20)
        self.assertIsNotNone(result)
    
if __name__ == '__main__':

    import logging

    suite = unittest.TestSuite((
        unittest.makeSuite(HClusterIntegerTestCase),
        unittest.makeSuite(HClusterSmallListTestCase),
        unittest.makeSuite(HClusterStringTestCase),
        unittest.makeSuite(Issue28TestCase),
    ))

    logging.basicConfig(level=logging.DEBUG)
    unittest.TextTestRunner(verbosity=2).run(suite)