1
2
3
4
5
6
7
8
9 """Unit tests for PyMVPA metrics"""
10
11
12 from mvpa.mappers.metric import *
13 from mvpa.clfs.distance import *
14 import unittest
15 import numpy as N
16
18 """Basic tests for metrics: neighbors etc
19 """
20
28
29
31 """Descrete metrics tests -- elementsizes etc"""
32
33
34 elsize = [-2.5, 1.5]
35 distance = 3
36
37
38 metric = DescreteMetric(elsize)
39
40
41 target = N.array([ [1, 2], [2, 1], [2, 2], [2, 3], [3, 2] ])
42 self.failUnless( (metric.getNeighbors([2, 2], 2.6) == target).all())
43
44
45 for point in metric.getNeighbor([2, 2], distance):
46 self.failUnless( cartesianDistance(point, [2,2]) <= distance)
47
48
49 metric = DescreteMetric(elsize, manhattenDistance)
50 for point in metric.getNeighbor([2, 2], distance):
51 self.failUnless( manhattenDistance(point, [2, 2]) <= distance)
52
53 metric.elementsize = [10, 1.5]
54 """We can reassign element size as a whole"""
55 self.failUnless((metric.elementsize == [10, 1.5]).all())
56
57 try:
58 metric.elementsize[1] = 1
59 self.fail(
60 msg="We should not be able to reassign parts of elementsize")
61 except RuntimeError:
62 pass
63
64 self.failUnless((metric.getNeighbors([2, 2], 2.6) ==
65 [t for t in target if t[0]==2]).all())
66 """Check if new elementsize is in effect for getNeighbors"""
67
68
70 """Test ability to provide compatmask
71 """
72
73
74 esize = [2, 3.3, 3, 3]
75
76
77 metric = DescreteMetric(esize, compatmask=[0, 1, 1, 1])
78
79
80
81
82 self.failUnless((metric.getNeighbors([0]*4, 1) ==
83 [[-1, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0]]).all())
84
85
86 self.failUnless((metric.getNeighbors([0]*4, [0, 4, 4, 4]) ==
87 [[0,-1,0,0],[0,0,-1,0],[0,0,0,-1],[0,0,0,0],
88 [0,0,0,1],[0,0,1,0],[0,1,0,0]]).all())
89
90
91 self.failUnless((metric.getNeighbors([0]*4, [2, 0, 0, 0]) ==
92 [[-1,0,0,0],[0,0,0,0],[1,0,0,0]]).all())
93
94
95 self.failUnless(len(metric.getNeighbors([0]*4, [7.9, 0, 0, 0])) == 9)
96
97
98 old_filter = metric.filter_coord.copy()
99 cm = metric.compatmask
100 cm[0] = 1
101 metric.compatmask = cm
102 self.failUnless((metric.compatmask == [True]*4).all())
103 self.failUnless((metric.getNeighbors([0]*4, 3) ==
104 [[-1, 0, 0, 0], [ 0, 0, -1, 0], [ 0, 0, 0, -1],
105 [ 0, 0, 0, 0], [ 0, 0, 0, 1], [ 0, 0, 1, 0],
106 [ 1, 0, 0, 0]]).all())
107 self.failUnless(N.any(old_filter != metric.filter_coord))
108
110 """Test if generator getNeighbor and method getNeighbors
111 return the right thing"""
112
113 class BM(Metric):
114 """ Class which overrides only getNeighbor
115 """
116 def getNeighbor(self):
117 for n in [4, 5, 6]: yield n
118
119 class CM(Metric):
120 """ Class which overrides only getNeighbor
121 """
122 def getNeighbors(self):
123 return [1, 2, 3]
124
125 b = BM()
126 self.failUnless(b.getNeighbors() == [4, 5, 6])
127 c = CM()
128 self.failUnless([ x for x in c.getNeighbor()] == [1, 2, 3])
129
130
132 """Create the suite -- pylint shut up"""
133 return unittest.makeSuite(MetricTests)
134
135
136 if __name__ == '__main__':
137 import runner
138