Debian Codegraph @

cluster/test/test_hierarchical.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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
46 class HClusterSmallListTestCase(Py23TestCase):
47 """
48 Test for Bug #1516204
49 """
50
51 def testClusterLen1(self):
52 """
53 Testing if hierarchical clustering a set of length 1 returns a set of
54 length 1
55 """
56 cl = HierarchicalClustering([876], lambda x, y: abs(x - y))
57 self.assertCItemsEqual([876], cl.getlevel(40))
58
59 def testClusterLen0(self):
60 """
61 Testing if hierarchical clustering an empty list returns an empty list
62 """
63 cl = HierarchicalClustering([], lambda x, y: abs(x - y))
64 self.assertEqual([], cl.getlevel(40))
65
66
67 class HClusterIntegerTestCase(Py23TestCase):
68
69 def setUp(self):
70 self.__data = [791, 956, 676, 124, 564, 84, 24, 365, 594, 940, 398,
71 971, 131, 365, 542, 336, 518, 835, 134, 391]
72
73 def testSingleLinkage(self):
74 "Basic Hierarchical Clustering test with integers"
75 cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y))
76 result = cl.getlevel(40)
77
78 # sort the values to make the tests less prone to algorithm changes
79 result = [sorted(_) for _ in result]
80 self.assertCItemsEqual([
81 [24],
82 [336, 365, 365, 391, 398],
83 [518, 542, 564, 594],
84 [676],
85 [791],
86 [835],
87 [84, 124, 131, 134],
88 [940, 956, 971],
89 ], result)
90
91 def testCompleteLinkage(self):
92 "Basic Hierarchical Clustering test with integers"
93 cl = HierarchicalClustering(self.__data,
94 lambda x, y: abs(x - y),
95 linkage='complete')
96 result = cl.getlevel(40)
97
98 # sort the values to make the tests less prone to algorithm changes
99 result = sorted([sorted(_) for _ in result])
100
101 expected = [
102 [24],
103 [84],
104 [124, 131, 134],
105 [336, 365, 365],
106 [391, 398],
107 [518],
108 [542, 564],
109 [594],
110 [676],
111 [791],
112 [835],
113 [940, 956, 971],
114 ]
115 self.assertEqual(result, expected)
116
117 def testUCLUS(self):
118 "Basic Hierarchical Clustering test with integers"
119 cl = HierarchicalClustering(self.__data,
120 lambda x, y: abs(x - y),
121 linkage='uclus')
122 expected = [
123 [24],
124 [84],
125 [124, 131, 134],
126 [336, 365, 365, 391, 398],
127 [518, 542, 564],
128 [594],
129 [676],
130 [791],
131 [835],
132 [940, 956, 971],
133 ]
134 result = sorted([sorted(_) for _ in cl.getlevel(40)])
135 self.assertEqual(result, expected)
136
137 def testAverageLinkage(self):
138 cl = HierarchicalClustering(self.__data,
139 lambda x, y: abs(x - y),
140 linkage='average')
141 # TODO: The current test-data does not really trigger a difference
142 # between UCLUS and "average" linkage.
143 expected = [
144 [24],
145 [84],
146 [124, 131, 134],
147 [336, 365, 365, 391, 398],
148 [518, 542, 564],
149 [594],
150 [676],
151 [791],
152 [835],
153 [940, 956, 971],
154 ]
155 result = sorted([sorted(_) for _ in cl.getlevel(40)])
156 self.assertEqual(result, expected)
157
158 def testUnmodifiedData(self):
159 cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y))
160 new_data = []
161 [new_data.extend(_) for _ in cl.getlevel(40)]
162 self.assertEqual(sorted(new_data), sorted(self.__data))
163
164 def testMultiprocessing(self):
165 cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y),
166 num_processes=4)
167 new_data = []
168 [new_data.extend(_) for _ in cl.getlevel(40)]
169 self.assertEqual(sorted(new_data), sorted(self.__data))
170
171
172 class HClusterStringTestCase(Py23TestCase):
173
174 def sim(self, x, y):
175 sm = SequenceMatcher(lambda x: x in ". -", x, y)
176 return 1 - sm.ratio()
177
178 def setUp(self):
179 self.__data = ("Lorem ipsum dolor sit amet consectetuer adipiscing "
180 "elit Ut elit Phasellus consequat ultricies mi Sed "
181 "congue leo at neque Nullam").split()
182
183 def testDataTypes(self):
184 "Test for bug #?"
185 cl = HierarchicalClustering(self.__data, self.sim)
186 for item in cl.getlevel(0.5):
187 self.assertEqual(
188 type(item), type([]),
189 "Every item should be a list!")
190
191 def testCluster(self):
192 "Basic Hierachical clustering test with strings"
193 self.skipTest('These values lead to non-deterministic results. '
194 'This makes it untestable!')
195 cl = HierarchicalClustering(self.__data, self.sim)
196 self.assertEqual([
197 ['ultricies'],
198 ['Sed'],
199 ['Phasellus'],
200 ['mi'],
201 ['Nullam'],
202 ['sit', 'elit', 'elit', 'Ut', 'amet', 'at'],
203 ['leo', 'Lorem', 'dolor'],
204 ['congue', 'neque', 'consectetuer', 'consequat'],
205 ['adipiscing'],
206 ['ipsum'],
207 ], cl.getlevel(0.5))
208
209 def testUnmodifiedData(self):
210 cl = HierarchicalClustering(self.__data, self.sim)
211 new_data = []
212 [new_data.extend(_) for _ in cl.getlevel(0.5)]
213 self.assertEqual(sorted(new_data), sorted(self.__data))
214
215
216 class HClusterTuplesTestCase(Py23TestCase):
217 '''
218 Test case to cover the case where the data contains tuple-items
219
220 See Github issue #20
221 '''
222
223 def testSingleLinkage(self):
224 "Basic Hierarchical Clustering test with integers"
225
226 def euclidian_distance(a, b):
227 return sqrt(sum([pow(z[0] - z[1], 2) for z in zip(a, b)]))
228
229 self.__data = [(1, 1), (1, 2), (1, 3)]
230 cl = HierarchicalClustering(self.__data, euclidian_distance)
231 result = cl.getlevel(40)
232 self.assertIsNotNone(result)
233
234 class Issue28TestCase(Py23TestCase):
235 '''
236 Test case to cover the case where the data consist
237 of dictionary keys, and the distance function executes
238 on the values these keys are associated with in the
239 dictionary, rather than the keys themselves.
240
241 Behaviour for this test case differs between Python2.7
242 and Python3.5: on 2.7 the test behaves as expected,
243
244 See Github issue #28.
245 '''
246
247 def testIssue28(self):
248 "Issue28 (Hierarchical Clustering)"
249
250 points1D = {
251 'p4' : 5, 'p2' : 6, 'p7' : 10,
252 'p9' : 120, 'p10' : 121, 'p11' : 119,
253 }
254
255 distance_func = lambda a,b : abs(points1D[a]-points1D[b])
256 cl = HierarchicalClustering(list(points1D.keys()), distance_func)
257 result = cl.getlevel(20)
258 self.assertIsNotNone(result)
259
260 if __name__ == '__main__':
261
262 import logging
263
264 suite = unittest.TestSuite((
265 unittest.makeSuite(HClusterIntegerTestCase),
266 unittest.makeSuite(HClusterSmallListTestCase),
267 unittest.makeSuite(HClusterStringTestCase),
268 unittest.makeSuite(Issue28TestCase),
269 ))
270
271 logging.basicConfig(level=logging.DEBUG)
272 unittest.TextTestRunner(verbosity=2).run(suite)