Debian Codegraph @

cluster/test/test_hierarchical.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #
2 # This is part of "python-cluster". A library to group similar items together.
3 # Copyright (C) 2006 Michel Albert
4 #
5 # This library is free software; you can redistribute it and/or modify it under
6 # the terms of the GNU Lesser General Public License as published by the Free
7 # Software Foundation; either version 2.1 of the License, or (at your option)
8 # any later version.
9 # This library is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12 # details.
13 # You should have received a copy of the GNU Lesser General Public License
14 # along with this library; if not, write to the Free Software Foundation, Inc.,
15 # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 #
17
18 """
19 Tests for hierarchical clustering.
20
21 .. note::
22
23 Even though the results are lists, the order of items in the resulting
24 clusters is non-deterministic. This should be taken into consideration when
25 writing "expected" values!
26 """
27
28 from difflib import SequenceMatcher
29 from math import sqrt
30 from sys import hexversion
31 import unittest
32
33 from cluster import HierarchicalClustering
34
35
36 class Py23TestCase(unittest.TestCase):
37
38 def __init__(self, *args, **kwargs):
39 super(Py23TestCase, self).__init__(*args, **kwargs)
40 if hexversion < 0x030000f0:
41 self.assertCItemsEqual = self.assertItemsEqual
42 else:
43 self.assertCItemsEqual = self.assertCountEqual
44
•45 def distance(x, y):
46 return abs(x - y)
47
48 class HClusterSmallListTestCase(Py23TestCase):
49 """
50 Test for Bug #1516204
51 """
52
53 def testClusterLen1(self):
54 """
55 Testing if hierarchical clustering a set of length 1 returns a set of
56 length 1
57 """
58 cl = HierarchicalClustering([876], lambda x, y: abs(x - y))
59 self.assertCItemsEqual([876], cl.getlevel(40))
60
61 def testClusterLen0(self):
62 """
63 Testing if hierarchical clustering an empty list returns an empty list
64 """
65 cl = HierarchicalClustering([], lambda x, y: abs(x - y))
66 self.assertEqual([], cl.getlevel(40))
67
68
69 class HClusterIntegerTestCase(Py23TestCase):
70
71 def setUp(self):
72 self.__data = [791, 956, 676, 124, 564, 84, 24, 365, 594, 940, 398,
73 971, 131, 365, 542, 336, 518, 835, 134, 391]
74
75 def testSingleLinkage(self):
76 "Basic Hierarchical Clustering test with integers"
77 cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y))
78 result = cl.getlevel(40)
79
80 # sort the values to make the tests less prone to algorithm changes
81 result = [sorted(_) for _ in result]
82 self.assertCItemsEqual([
83 [24],
84 [336, 365, 365, 391, 398],
85 [518, 542, 564, 594],
86 [676],
87 [791],
88 [835],
89 [84, 124, 131, 134],
90 [940, 956, 971],
91 ], result)
92
93 def testCompleteLinkage(self):
94 "Basic Hierarchical Clustering test with integers"
95 cl = HierarchicalClustering(self.__data,
96 lambda x, y: abs(x - y),
97 linkage='complete')
98 result = cl.getlevel(40)
99
100 # sort the values to make the tests less prone to algorithm changes
101 result = sorted([sorted(_) for _ in result])
102
103 expected = [
104 [24],
105 [84],
106 [124, 131, 134],
107 [336, 365, 365],
108 [391, 398],
109 [518],
110 [542, 564],
111 [594],
112 [676],
113 [791],
114 [835],
115 [940, 956, 971],
116 ]
117 self.assertEqual(result, expected)
118
119 def testUCLUS(self):
120 "Basic Hierarchical Clustering test with integers"
121 cl = HierarchicalClustering(self.__data,
122 lambda x, y: abs(x - y),
123 linkage='uclus')
124 expected = [
125 [24],
126 [84],
127 [124, 131, 134],
128 [336, 365, 365, 391, 398],
129 [518, 542, 564],
130 [594],
131 [676],
132 [791],
133 [835],
134 [940, 956, 971],
135 ]
136 result = sorted([sorted(_) for _ in cl.getlevel(40)])
137 self.assertEqual(result, expected)
138
139 def testAverageLinkage(self):
140 cl = HierarchicalClustering(self.__data,
141 lambda x, y: abs(x - y),
142 linkage='average')
143 # TODO: The current test-data does not really trigger a difference
144 # between UCLUS and "average" linkage.
145 expected = [
146 [24],
147 [84],
148 [124, 131, 134],
149 [336, 365, 365, 391, 398],
150 [518, 542, 564],
151 [594],
152 [676],
153 [791],
154 [835],
155 [940, 956, 971],
156 ]
157 result = sorted([sorted(_) for _ in cl.getlevel(40)])
158 self.assertEqual(result, expected)
159
160 def testUnmodifiedData(self):
161 cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y))
162 new_data = []
163 [new_data.extend(_) for _ in cl.getlevel(40)]
164 self.assertEqual(sorted(new_data), sorted(self.__data))
165
166 def testMultiprocessing(self):
•167 cl = HierarchicalClustering(self.__data, distance, num_processes=4)
168 new_data = []
169 [new_data.extend(_) for _ in cl.getlevel(40)]
170 self.assertEqual(sorted(new_data), sorted(self.__data))
171
172
173 class HClusterStringTestCase(Py23TestCase):
174
175 def sim(self, x, y):
176 sm = SequenceMatcher(lambda x: x in ". -", x, y)
177 return 1 - sm.ratio()
178
179 def setUp(self):
180 self.__data = ("Lorem ipsum dolor sit amet consectetuer adipiscing "
181 "elit Ut elit Phasellus consequat ultricies mi Sed "
182 "congue leo at neque Nullam").split()
183
184 def testDataTypes(self):
185 "Test for bug #?"
186 cl = HierarchicalClustering(self.__data, self.sim)
187 for item in cl.getlevel(0.5):
188 self.assertEqual(
189 type(item), type([]),
190 "Every item should be a list!")
191
192 def testCluster(self):
193 "Basic Hierachical clustering test with strings"
194 self.skipTest('These values lead to non-deterministic results. '
195 'This makes it untestable!')
196 cl = HierarchicalClustering(self.__data, self.sim)
197 self.assertEqual([
198 ['ultricies'],
199 ['Sed'],
200 ['Phasellus'],
201 ['mi'],
202 ['Nullam'],
203 ['sit', 'elit', 'elit', 'Ut', 'amet', 'at'],
204 ['leo', 'Lorem', 'dolor'],
205 ['congue', 'neque', 'consectetuer', 'consequat'],
206 ['adipiscing'],
207 ['ipsum'],
208 ], cl.getlevel(0.5))
209
210 def testUnmodifiedData(self):
211 cl = HierarchicalClustering(self.__data, self.sim)
212 new_data = []
213 [new_data.extend(_) for _ in cl.getlevel(0.5)]
214 self.assertEqual(sorted(new_data), sorted(self.__data))
215
216
217 class HClusterTuplesTestCase(Py23TestCase):
218 '''
219 Test case to cover the case where the data contains tuple-items
220
221 See Github issue #20
222 '''
223
224 def testSingleLinkage(self):
225 "Basic Hierarchical Clustering test with integers"
226
227 def euclidian_distance(a, b):
228 return sqrt(sum([pow(z[0] - z[1], 2) for z in zip(a, b)]))
229
230 self.__data = [(1, 1), (1, 2), (1, 3)]
231 cl = HierarchicalClustering(self.__data, euclidian_distance)
232 result = cl.getlevel(40)
233 self.assertIsNotNone(result)
234
235 class Issue28TestCase(Py23TestCase):
236 '''
237 Test case to cover the case where the data consist
238 of dictionary keys, and the distance function executes
239 on the values these keys are associated with in the
240 dictionary, rather than the keys themselves.
241
242 Behaviour for this test case differs between Python2.7
243 and Python3.5: on 2.7 the test behaves as expected,
244
245 See Github issue #28.
246 '''
247
248 def testIssue28(self):
249 "Issue28 (Hierarchical Clustering)"
250
251 points1D = {
252 'p4' : 5, 'p2' : 6, 'p7' : 10,
253 'p9' : 120, 'p10' : 121, 'p11' : 119,
254 }
255
256 distance_func = lambda a,b : abs(points1D[a]-points1D[b])
257 cl = HierarchicalClustering(list(points1D.keys()), distance_func)
258 result = cl.getlevel(20)
259 self.assertIsNotNone(result)
260
261 if __name__ == '__main__':
262
263 import logging
264
265 suite = unittest.TestSuite((
266 unittest.makeSuite(HClusterIntegerTestCase),
267 unittest.makeSuite(HClusterSmallListTestCase),
268 unittest.makeSuite(HClusterStringTestCase),
269 unittest.makeSuite(Issue28TestCase),
270 ))
271
272 logging.basicConfig(level=logging.DEBUG)
273 unittest.TextTestRunner(verbosity=2).run(suite)