Debian Codegraph @

csb/test/cases/numeric/__init__.py

raw
1 import csb.test as test
2 import numpy as np
3
4
5 @test.regression
6 class MathRegressions(test.Case):
7
8 def testDihedralAngles(self):
9 """
10 r526
11 """
12 from csb.numeric import dihedral_angle
13
14 a = np.array([2, 0., 0.])
15 b = np.array([0, 0., 0.])
16 c = np.array([0, 2., 0.])
17 d = np.array([0, 4., -4.])
18
19 self.assertEqual(dihedral_angle(a, b, c, d), 90.0)
20 self.assertEqual(dihedral_angle(a, b, c, a), 0.0)
21 self.assertEqual(dihedral_angle(a, b, c, -d), -90.0)
22
23
24
25 @test.unit
26 class TestMath(test.Case):
27
28 def testDihedralAngles(self):
29 from csb.numeric import dihedral_angle
30
31 a = np.array([1, 0., 0.])
32 b = np.array([0, 0., 0.])
33 c = np.array([0, 1., 0.])
34 d = np.array([0, 1., -1.])
35
36 self.assertEqual(dihedral_angle(a, b, c, d), 90.0)
37 self.assertEqual(dihedral_angle(a, b, c, d + a), 45.0)
38 self.assertEqual(dihedral_angle(a, b, c, a), 0.0)
39 self.assertEqual(dihedral_angle(a, b, c, -d), -90.0)
40
41 def testLog(self):
42 from csb.numeric import log, LOG_MAX, LOG_MIN
43 from numpy import log as ref_log
44
45 x = np.linspace(LOG_MIN, LOG_MAX, 1000000)
46
47 self.assertTrue((log(x) == ref_log(x)).all())
48 self.assertEqual(log(10 * LOG_MAX), log(LOG_MAX))
49 self.assertEqual(log(0.1 * LOG_MIN), log(LOG_MIN))
50
51
52 def testExp(self):
53 from csb.numeric import exp, EXP_MAX, EXP_MIN
54 from numpy import exp as ref_exp
55
56 x = np.linspace(EXP_MIN,
57 EXP_MAX, 100000)
58
59 self.assertTrue((exp(x) == ref_exp(x)).all())
60 self.assertEqual(exp(EXP_MAX + 10.), exp(EXP_MAX))
61 self.assertEqual(exp(10. * EXP_MIN), exp(EXP_MIN))
62
63 def testPolar(self):
64 from csb.numeric import polar, from_polar
65
66 rand = np.random.random((10000, 3))
67 result = np.array(list(map(polar, map(from_polar, rand))))
68
69 eps = 1e-8
70 self.assertTrue((np.abs(rand - result) < eps).all())
71 self.assertTrue((np.abs(polar(np.array([0., 1.0])) - \
72 np.array([1., np.pi * 0.5])) < eps).all())
73
74 def testFromPolar(self):
75 from csb.numeric import polar, from_polar
76
77 rand = np.random.random((10000, 3))
78 result = np.array(list(map(from_polar, map(polar, rand))))
79
80 eps = 1e-8
81 self.assertTrue((np.abs(rand - result) < eps).all())
82 self.assertTrue((np.abs(from_polar(np.array([1., np.pi * 0.5])) - \
83 np.array([0., 1.0])) < eps).all())
84
85 def testRadian2Degree(self):
86 from csb.numeric import degree2radian, radian2degree
87
88 rand = np.random.random(10000) * 2 * np.pi
89 eps = 1e-8
90
91 self.assertTrue((np.abs(rand -
92 degree2radian(radian2degree(rand)))\
93 < eps).all())
94
95 def testDegree2Radian(self):
96 from csb.numeric import degree2radian, radian2degree
97
98 rand = np.random.random(10000) * 2 * np.pi
99 eps = 1e-8
100
101 self.assertTrue((np.abs(rand -
102 degree2radian(radian2degree(rand)))\
103 < eps).all())
104
105 def testRotationMatrix(self):
106 from csb.numeric import rotation_matrix, axis_and_angle
107
108 R1 = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]]
109 R2 = rotation_matrix([0, 0, 1], np.pi / 2.0)
110 axis, angle = axis_and_angle(R2)
111 R3 = rotation_matrix(axis, angle)
112
113 self.assertAlmostEqual(angle, np.pi / 2.0)
114 self.assertTrue(np.allclose(R1, R2))
115 self.assertTrue(np.allclose(R1, R3))
116
117
118 @test.unit
119 class TestNumeric(test.Case):
120
121 def testTrapezoidal(self):
122 from csb.numeric import trapezoidal, exp
123
124 x = np.linspace(-10., 10, 1000)
125 y = exp(-0.5 * x * x) / np.sqrt(2 * np.pi)
126
127 self.assertAlmostEqual(trapezoidal(x, y), 1.0, 10)
128
129 def testLogTrapezoidal(self):
130 from csb.numeric import log_trapezoidal, log
131
132 x = np.linspace(-100., 100, 1000)
133 y = -0.5 * x * x - log(np.sqrt(2 * np.pi))
134
135 self.assertTrue(abs(log_trapezoidal(y, x)) <= 1e-8)
136
137 def testTrapezoidal2D(self):
138 from csb.numeric import trapezoidal_2d, exp
139 from numpy import pi
140
141 xx = np.linspace(-10., 10, 500)
142 yy = np.linspace(-10., 10, 500)
143
144 X, Y = np.meshgrid(xx, yy)
145 x = np.array(list(zip(np.ravel(X), np.ravel(Y))))
146
147 # mean = np.zeros((2,))
148 cov = np.eye(2)
149 mu = np.ones(2)
150 # D = 2
151 q = np.sqrt(np.clip(np.sum((x - mu) * np.dot(x - mu, np.linalg.inv(cov).T), -1), 0., 1e308))
152 f = exp(-0.5 * q ** 2) / ((2 * pi) * np.sqrt(np.abs(np.linalg.det(cov))))
153 f = f.reshape((len(xx), len(yy)))
154 I = trapezoidal_2d(f) * (xx[1] - xx[0]) * (yy[1] - yy[0])
155
156 self.assertTrue(abs(I - 1.) <= 1e-8)
157
158 def testSimpson2D(self):
159 from csb.numeric import simpson_2d, exp
160 from numpy import pi
161
162 xx = np.linspace(-10., 10, 500)
163 yy = np.linspace(-10., 10, 500)
164
165 X, Y = np.meshgrid(xx, yy)
166 x = np.array(list(zip(np.ravel(X), np.ravel(Y))))
167
168 # mean = np.zeros((2,))
169 cov = np.eye(2)
170 mu = np.ones(2)
171 # D = 2
172 q = np.sqrt(np.clip(np.sum((x - mu) * np.dot(x - mu, np.linalg.inv(cov).T), -1), 0., 1e308))
173 f = exp(-0.5 * q ** 2) / ((2 * pi) * np.sqrt(np.abs(np.linalg.det(cov))))
174 f = f.reshape((len(xx), len(yy)))
175 I = simpson_2d(f) * (xx[1] - xx[0]) * (yy[1] - yy[0])
176
177 self.assertTrue(abs(I - 1.) <= 1e-8)
178
179 def testLogTrapezoidal2D(self):
180 from csb.numeric import log_trapezoidal_2d, log
181 from numpy import pi
182
183 xx = np.linspace(-10., 10, 500)
184 yy = np.linspace(-10., 10, 500)
185
186 X, Y = np.meshgrid(xx, yy)
187 x = np.array(list(zip(np.ravel(X), np.ravel(Y))))
188
189 # mean = np.zeros((2,))
190 cov = np.eye(2)
191 mu = np.ones(2)
192 # D = 2
193 q = np.sqrt(np.clip(np.sum((x - mu) * np.dot(x - mu, np.linalg.inv(cov).T), -1), 0., 1e308))
194 f = -0.5 * q ** 2 - log((2 * pi) * np.sqrt(np.abs(np.linalg.det(cov))))
195 f = f.reshape((len(xx), len(yy)))
196
197 logI = log_trapezoidal_2d(f, xx, yy)
198
199 self.assertTrue(abs(logI) <= 1e-8)
200
201 @test.functional
202 class InvertibleMatrixTest(test.Case):
203
204
205 d = 100
206 # Find some random invertible matrix
207 m_general = np.random.uniform(low=-2, high=2, size=(d, d))
208 while np.linalg.det(m_general) == 0:
209 m_general = np.random.uniform(low=-2, high=2, size=(d, d))
210
211
212 m_general_inv = np.linalg.inv(m_general)
213 m_diagonal = np.diag(np.random.uniform(low=-2, high=2, size=d))
214 m_diagonal_inv = np.linalg.inv(m_diagonal)
215 m_2unity = np.eye(d) * 2.
216 m_2unity_inv = np.linalg.inv(m_2unity)
217
218 def invertMatrix(self, matrix):
219 from csb.numeric import InvertibleMatrix
220
221 for i in range(1000):
222 testmatrix = InvertibleMatrix(matrix)
223 dummy = testmatrix.inverse
224
225 @test.skip("machine-specific")
226 def testDiagonalTweak(self):
227
228 self.assertFasterThan(0.75, self.invertMatrix, self.m_diagonal)
229
230 @test.skip("machine-specific")
231 def testUnityMultipleTweak(self):
232
233 self.assertFasterThan(0.5, self.invertMatrix, self.m_2unity)
234
235 def testCaching(self):
236 from csb.numeric import InvertibleMatrix
237
238 # Initialize with matrix
239 testmatrix = InvertibleMatrix(self.m_general)
240 # Check if it worked
241 self.assertListAlmostEqual(testmatrix._matrix.flatten().tolist(),
242 self.m_general.flatten().tolist())
243 # Because the testmatrix.inverse hasn't been accessed yet, testmatrix._inverse should be None
244 self.assertEqual(testmatrix._inverse_matrix, None)
245 # Now we access testmatrix.inverse, which onyl now actually calculates the inverse
246 self.assertListAlmostEqual(testmatrix.inverse.flatten().tolist(),
247 self.m_general_inv.flatten().tolist())
248
249 # Let's change testmatrix via testmatrix.__imul__
250 testmatrix *= 2.
251 # Check if that worked
252 self.assertListAlmostEqual(testmatrix._matrix.flatten().tolist(),
253 (2.0 * self.m_general.flatten()).tolist())
254 # This operation should not have changed the testmatrix._inverse_matrix field, as
255 # we didn't access testmatrix.inverse again
256 self.assertListAlmostEqual(testmatrix._inverse_matrix.flatten().tolist(),
257 self.m_general_inv.flatten().tolist())
258 # New we access testmatrix.inverse, which calculates the inverse and updates the field
259 self.assertListAlmostEqual(testmatrix.inverse.flatten().tolist(),
260 (self.m_general_inv / 2.0).flatten().tolist())
261
262 # The same again for testmatrix.__idiv__
263 testmatrix /= 2.
264 # Check if that worked
265 self.assertListAlmostEqual(testmatrix._matrix.flatten().tolist(),
266 (self.m_general.flatten()).tolist())
267 # This operation should not have changed the testmatrix._inverse_matrix field, as
268 # we didn't access testmatrix.inverse again
269 self.assertListAlmostEqual(testmatrix._inverse_matrix.flatten().tolist(),
270 (self.m_general_inv / 2.0).flatten().tolist())
271 # New we access testmatrix.inverse, which calculates the inverse and updates the field
272 self.assertListAlmostEqual(testmatrix.inverse.flatten().tolist(),
273 self.m_general_inv.flatten().tolist())
274
275 # Initialize with inverse matrix
276 testmatrix = InvertibleMatrix(inverse_matrix=self.m_general_inv)
277 # Let's see if that worked, e.g. if the testmatrix._inverse_matrix field has been
278 # set correctly
279 self.assertListAlmostEqual(testmatrix._inverse_matrix.flatten().tolist(),
280 self.m_general_inv.flatten().tolist())
281 # Check if the property returns what it's supposed to be
282 self.assertListAlmostEqual(testmatrix.inverse.flatten().tolist(),
283 self.m_general_inv.flatten().tolist())
284 # We didn't call testmatrix.__getitem__() yet, so testmatrix._matrix should be None
285 self.assertEqual(testmatrix._matrix, None)
286 # To include the numerical error
287 invinv = np.linalg.inv(self.m_general_inv)
288 # Now we access testmatrix by its __getitem__ method, which calculates the
289 # testmatrix._matrix field from the testmatrix._inverse_matrix by inversion
290 for i in range(len(testmatrix)):
291 self.assertListAlmostEqual(testmatrix[i].tolist(), invinv[i].tolist())
292
293 testmatrix = InvertibleMatrix(inverse_matrix=self.m_general_inv)
294 # Let's change testmatrix via testmatrix.__imul__
295 testmatrix *= 2.
296 # That shouldn't have changed the testmatrix._matrix field (which currently
297 # should be None), but the testmatrix._inverse_matrix field by a factor of 1/2.0 = 0.5
298 self.assertEqual(testmatrix._matrix, None)
299 self.assertListAlmostEqual(testmatrix._inverse_matrix.flatten().tolist(),
300 (self.m_general_inv / 2.0).flatten().tolist())
301 # Now we access testmatrix by __getitem__, which calculates the matrix
302 # from the inverse and updates the field testmatrix._matrix
303 invinv *= 2.0
304 for i in range(len(testmatrix)):
305 self.assertListAlmostEqual(testmatrix[i].tolist(), invinv[i].tolist())
306
307 # The same again for testmatrix.__idiv__
308 testmatrix = InvertibleMatrix(inverse_matrix=self.m_general_inv)
309 testmatrix /= 2.
310 # Check if testmatrix._matrix is None and if the testmatrix._inverse field
311 # has been multiplied by a factor of 2.0
312 self.assertEqual(testmatrix._matrix, None)
313 self.assertListAlmostEqual(testmatrix.inverse.flatten().tolist(),
314 (self.m_general_inv * 2.0).flatten().tolist())
315 # All that is supposed to leave testmatrix._matrix with None:
316 self.assertEqual(testmatrix._matrix, None)
317 # Now we access testmatrix by __getitem__ again, which calculates the matrix from
318 # its inverse and updates the field
319 invinv /= 4.0
320 for i in range(len(testmatrix)):
321 self.assertListAlmostEqual(testmatrix[i].tolist(), invinv[i].tolist())
322
323 def assertListAlmostEqual(self, first, second, places=None, msg=None, delta=0.00000001):
324
325 for i, j in zip(first, second):
326 self.assertAlmostEqual(i, j, places=places, msg=msg, delta=delta)
327
328 if __name__ == '__main__':
329 test.Console()
330