Repository navigation
Expand file tree
/
Copy pathtest.py
More file actions
309 lines (252 loc) · 10 KB
/
Copy pathtest.py
File metadata and controls
309 lines (252 loc) · 10 KB
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#
# 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
#
from difflib import SequenceMatcher
from os import urandom
from random import randint
import unittest
try:
import numpy
NUMPY_AVAILABLE = True
except:
NUMPY_AVAILABLE = False
from cluster import (HierarchicalClustering, KMeansClustering, ClusteringError)
import cluster.util as util
def compare_list(x, y):
"""
Compare lists by content. Ordering does not matter.
Returns True if both lists contain the same items (and are of identical
length)
"""
cmpx = [set(cluster) for cluster in x]
cmpy = [set(cluster) for cluster in y]
all_ok = True
for cset in cmpx:
all_ok &= cset in cmpy
for cset in cmpy:
all_ok &= cset in cmpx
return all_ok
class MyObject(object):
"""
A custom data object used in some tests.
"""
def __init__(self, value, uid=None):
self.value = value
self.uid = uid or urandom(10).encode('base64').strip()
def __repr__(self):
return 'MyObject({!r}, {!r})'.format(self.value, self.uid)
class HClusterSmallListTestCase(unittest.TestCase):
"""
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.assertEqual([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(unittest.TestCase):
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 testCluster(self):
"Basic Hierarchical Clustering test with integers"
cl = HierarchicalClustering(self.__data, lambda x, y: abs(x - y))
cl.cluster()
self.assertEqual([
[24],
[84, 124, 131, 134],
[336, 365, 365, 365, 398, 391],
[940, 956, 971],
[791],
[835],
[676],
[518, 564, 542]],
cl.getlevel(40))
class HClusterStringTestCase(unittest.TestCase):
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"
cl = HierarchicalClustering(self.__data, self.sim)
self.assertEqual([
['Nullam.'],
['Sed'],
['mi.'],
['ultricies'],
['Phasellus'],
['amet,', 'at'],
['sit', 'elit.', 'elit.', 'elit.'],
['leo', 'Lorem', 'dolor'],
['neque.', 'congue', 'consectetuer', 'consequat'],
['ipsum'],
['adipiscing']
],
cl.getlevel(0.5))
class KClusterSmallListTestCase(unittest.TestCase):
def testClusterLen1(self):
"Testing that a search space of length 1 returns only one cluster"
cl = KMeansClustering([876])
self.assertEqual([876], cl.getclusters(2))
self.assertEqual([876], cl.getclusters(5))
def testClusterLen0(self):
"Testing if clustering an empty set, returns an empty set"
cl = KMeansClustering([])
self.assertEqual([], cl.getclusters(2))
self.assertEqual([], cl.getclusters(7))
class KCluster2DTestCase(unittest.TestCase):
def testClusterCount(self):
"Test that asking for less than 2 clusters raises an error"
cl = KMeansClustering([876, 123, 344, 676],
distance=lambda x, y: abs(x - y))
self.assertRaises(ClusteringError, cl.getclusters, 0)
self.assertRaises(ClusteringError, cl.getclusters, 1)
def testNonsenseCluster(self):
"""
Test that asking for more clusters than data-items available raises an
error
"""
cl = KMeansClustering([876, 123], distance=lambda x, y: abs(x - y))
self.assertRaises(ClusteringError, cl.getclusters, 5)
def testUniformLength(self):
"""
Test if there is an item in the cluster that has a different
cardinality
"""
data = [(1, 5), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6, 7), (7, 3), (8,
1), (8, 2), (8), (9, 2), (9, 3)]
self.assertRaises(ValueError, KMeansClustering, data)
def testPointDoubling(self):
"test for bug #1604868"
data = [(18, 13), (15, 12), (17, 12), (18, 12), (19, 12), (16, 11),
(18, 11), (19, 10), (0, 0), (1, 4), (1, 2), (2, 3), (4, 1),
(4, 3), (5, 2), (6, 1)]
cl = KMeansClustering(data)
clusters = cl.getclusters(2)
expected = [[(18, 13), (15, 12), (17, 12), (18, 12), (19, 12), (16,
11), (18, 11), (19, 10)], [(0, 0), (1, 4), (1, 2), (2, 3), (4, 1),
(5, 2), (6, 1), (4, 3)]]
self.assertTrue(compare_list(
clusters,
expected),
"Elements differ!\n%s\n%s" % (clusters, expected))
def testClustering(self):
"Basic clustering test"
data = [(8, 2), (7, 3), (2, 6), (3, 5), (3, 6), (1, 5), (8, 1), (3,
4), (8, 3), (9, 2), (2, 5), (9, 3)]
cl = KMeansClustering(data)
self.assertEqual(
cl.getclusters(2),
[[(8, 2), (8, 1), (8, 3), (7, 3), (9, 2), (9, 3)],
[(3, 5), (1, 5), (3, 4), (2, 6), (2, 5), (3, 6)]])
class KClusterSFBugs(unittest.TestCase):
def testLostFunctionReference(self):
"test for bug #1727558"
cl = KMeansClustering([(1, 1), (20, 40), (20, 41)],
lambda x, y: x + y)
clusters = cl.getclusters(3)
expected = [(1, 1), (20, 40), (20, 41)]
self.assertTrue(compare_list(
clusters,
expected),
"Elements differ!\n%s\n%s" % (clusters, expected))
def testMultidimArray(self):
from random import random
data = []
for _ in range(200):
data.append([random(), random()])
cl = KMeansClustering(data, lambda p0, p1: (
p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2)
cl.getclusters(10)
class KClusterGithubIssues(unittest.TestCase):
def test_custom_object_data(self):
self.skipTest("temporarily skipped until centroid is solved")
data = [MyObject(randint(0, 1000)) for _ in range(40)]
cl = KMeansClustering(data, lambda x, y: float(abs(x.value-y.value)))
clustered = cl.getclusters(10)
print(clustered)
self.fail()
class TestUtils(unittest.TestCase):
def test_default_centroid(self):
result = util.centroid([
(1, 2, 3),
(2, 3, 4),
(3, 4, 5),
(4, 5, 6),
])
self.assertEqual(result, (2.5, 3.5, 4.5))
def test_custom_centroid_fold(self):
result = util.centroid([
MyObject((1, 2, 3), 1),
MyObject((2, 3, 4), 2),
MyObject((3, 4, 5), 3),
MyObject((4, 5, 6), 4),
])
self.assertEqual(result, (2.5, 3.5, 4.5))
def test_custom_centroid_getter(self):
result = util.centroid([
MyObject((1, 2, 3), 1),
MyObject((2, 3, 4), 2),
MyObject((3, 4, 5), 3),
MyObject((4, 5, 6), 4),
], getter=lambda x: x.value)
self.assertEqual(result, (2.5, 3.5, 4.5))
def test_custom2_centroid_getter(self):
result = util.centroid([
MyObject(1, 1),
MyObject(2, 2),
MyObject(3, 3),
MyObject(4, 4),
], getter=lambda x: x.value)
self.assertEqual(result, 2.5)
@unittest.skipUnless(NUMPY_AVAILABLE,
'numpy not available. Associated test will not be loaded!')
class NumpyTests(unittest.TestCase):
def testNumpyRandom(self):
data = numpy.random.rand(500, 2)
cl = KMeansClustering(data, lambda p0, p1: (
p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2, numpy.array_equal)
cl.getclusters(10)
if __name__ == '__main__':
suite = unittest.TestSuite((
unittest.makeSuite(HClusterIntegerTestCase),
unittest.makeSuite(HClusterSmallListTestCase),
unittest.makeSuite(HClusterStringTestCase),
unittest.makeSuite(KCluster2DTestCase),
unittest.makeSuite(KClusterSFBugs)),
unittest.makeSuite(KClusterSmallListTestCase),
unittest.makeSuite(NumpyTests),
)
unittest.TextTestRunner(verbosity=2).run(suite)