comparison DEPENDENCIES/mingw32/Python27/Lib/site-packages/numpy/linalg/tests/test_linalg.py @ 87:2a2c65a20a8b

Add Python libs and headers
author Chris Cannam
date Wed, 25 Feb 2015 14:05:22 +0000
parents
children
comparison
equal deleted inserted replaced
86:413a9d26189e 87:2a2c65a20a8b
1 """ Test functions for linalg module
2
3 """
4 from __future__ import division, absolute_import, print_function
5
6 import os
7 import sys
8 import itertools
9 import traceback
10
11 import numpy as np
12 from numpy import array, single, double, csingle, cdouble, dot, identity
13 from numpy import multiply, atleast_2d, inf, asarray, matrix
14 from numpy import linalg
15 from numpy.linalg import matrix_power, norm, matrix_rank
16 from numpy.testing import (
17 assert_, assert_equal, assert_raises, assert_array_equal,
18 assert_almost_equal, assert_allclose, run_module_suite,
19 dec
20 )
21
22
23 def ifthen(a, b):
24 return not a or b
25
26
27 def imply(a, b):
28 return not a or b
29
30
31 old_assert_almost_equal = assert_almost_equal
32
33
34 def assert_almost_equal(a, b, **kw):
35 if asarray(a).dtype.type in (single, csingle):
36 decimal = 6
37 else:
38 decimal = 12
39 old_assert_almost_equal(a, b, decimal=decimal, **kw)
40
41
42 def get_real_dtype(dtype):
43 return {single: single, double: double,
44 csingle: single, cdouble: double}[dtype]
45
46
47 def get_complex_dtype(dtype):
48 return {single: csingle, double: cdouble,
49 csingle: csingle, cdouble: cdouble}[dtype]
50
51 def get_rtol(dtype):
52 # Choose a safe rtol
53 if dtype in (single, csingle):
54 return 1e-5
55 else:
56 return 1e-11
57
58 class LinalgCase(object):
59 def __init__(self, name, a, b, exception_cls=None):
60 assert isinstance(name, str)
61 self.name = name
62 self.a = a
63 self.b = b
64 self.exception_cls = exception_cls
65
66 def check(self, do):
67 if self.exception_cls is None:
68 do(self.a, self.b)
69 else:
70 assert_raises(self.exception_cls, do, self.a, self.b)
71
72 def __repr__(self):
73 return "<LinalgCase: %s>" % (self.name,)
74
75
76 #
77 # Base test cases
78 #
79
80 np.random.seed(1234)
81
82 SQUARE_CASES = [
83 LinalgCase("single",
84 array([[1., 2.], [3., 4.]], dtype=single),
85 array([2., 1.], dtype=single)),
86 LinalgCase("double",
87 array([[1., 2.], [3., 4.]], dtype=double),
88 array([2., 1.], dtype=double)),
89 LinalgCase("double_2",
90 array([[1., 2.], [3., 4.]], dtype=double),
91 array([[2., 1., 4.], [3., 4., 6.]], dtype=double)),
92 LinalgCase("csingle",
93 array([[1.+2j, 2+3j], [3+4j, 4+5j]], dtype=csingle),
94 array([2.+1j, 1.+2j], dtype=csingle)),
95 LinalgCase("cdouble",
96 array([[1.+2j, 2+3j], [3+4j, 4+5j]], dtype=cdouble),
97 array([2.+1j, 1.+2j], dtype=cdouble)),
98 LinalgCase("cdouble_2",
99 array([[1.+2j, 2+3j], [3+4j, 4+5j]], dtype=cdouble),
100 array([[2.+1j, 1.+2j, 1+3j], [1-2j, 1-3j, 1-6j]], dtype=cdouble)),
101 LinalgCase("empty",
102 atleast_2d(array([], dtype = double)),
103 atleast_2d(array([], dtype = double)),
104 linalg.LinAlgError),
105 LinalgCase("8x8",
106 np.random.rand(8, 8),
107 np.random.rand(8)),
108 LinalgCase("1x1",
109 np.random.rand(1, 1),
110 np.random.rand(1)),
111 LinalgCase("nonarray",
112 [[1, 2], [3, 4]],
113 [2, 1]),
114 LinalgCase("matrix_b_only",
115 array([[1., 2.], [3., 4.]]),
116 matrix([2., 1.]).T),
117 LinalgCase("matrix_a_and_b",
118 matrix([[1., 2.], [3., 4.]]),
119 matrix([2., 1.]).T),
120 ]
121
122 NONSQUARE_CASES = [
123 LinalgCase("single_nsq_1",
124 array([[1., 2., 3.], [3., 4., 6.]], dtype=single),
125 array([2., 1.], dtype=single)),
126 LinalgCase("single_nsq_2",
127 array([[1., 2.], [3., 4.], [5., 6.]], dtype=single),
128 array([2., 1., 3.], dtype=single)),
129 LinalgCase("double_nsq_1",
130 array([[1., 2., 3.], [3., 4., 6.]], dtype=double),
131 array([2., 1.], dtype=double)),
132 LinalgCase("double_nsq_2",
133 array([[1., 2.], [3., 4.], [5., 6.]], dtype=double),
134 array([2., 1., 3.], dtype=double)),
135 LinalgCase("csingle_nsq_1",
136 array([[1.+1j, 2.+2j, 3.-3j], [3.-5j, 4.+9j, 6.+2j]], dtype=csingle),
137 array([2.+1j, 1.+2j], dtype=csingle)),
138 LinalgCase("csingle_nsq_2",
139 array([[1.+1j, 2.+2j], [3.-3j, 4.-9j], [5.-4j, 6.+8j]], dtype=csingle),
140 array([2.+1j, 1.+2j, 3.-3j], dtype=csingle)),
141 LinalgCase("cdouble_nsq_1",
142 array([[1.+1j, 2.+2j, 3.-3j], [3.-5j, 4.+9j, 6.+2j]], dtype=cdouble),
143 array([2.+1j, 1.+2j], dtype=cdouble)),
144 LinalgCase("cdouble_nsq_2",
145 array([[1.+1j, 2.+2j], [3.-3j, 4.-9j], [5.-4j, 6.+8j]], dtype=cdouble),
146 array([2.+1j, 1.+2j, 3.-3j], dtype=cdouble)),
147 LinalgCase("cdouble_nsq_1_2",
148 array([[1.+1j, 2.+2j, 3.-3j], [3.-5j, 4.+9j, 6.+2j]], dtype=cdouble),
149 array([[2.+1j, 1.+2j], [1-1j, 2-2j]], dtype=cdouble)),
150 LinalgCase("cdouble_nsq_2_2",
151 array([[1.+1j, 2.+2j], [3.-3j, 4.-9j], [5.-4j, 6.+8j]], dtype=cdouble),
152 array([[2.+1j, 1.+2j], [1-1j, 2-2j], [1-1j, 2-2j]], dtype=cdouble)),
153 LinalgCase("8x11",
154 np.random.rand(8, 11),
155 np.random.rand(11)),
156 LinalgCase("1x5",
157 np.random.rand(1, 5),
158 np.random.rand(5)),
159 LinalgCase("5x1",
160 np.random.rand(5, 1),
161 np.random.rand(1)),
162 ]
163
164 HERMITIAN_CASES = [
165 LinalgCase("hsingle",
166 array([[1., 2.], [2., 1.]], dtype=single),
167 None),
168 LinalgCase("hdouble",
169 array([[1., 2.], [2., 1.]], dtype=double),
170 None),
171 LinalgCase("hcsingle",
172 array([[1., 2+3j], [2-3j, 1]], dtype=csingle),
173 None),
174 LinalgCase("hcdouble",
175 array([[1., 2+3j], [2-3j, 1]], dtype=cdouble),
176 None),
177 LinalgCase("hempty",
178 atleast_2d(array([], dtype = double)),
179 None,
180 linalg.LinAlgError),
181 LinalgCase("hnonarray",
182 [[1, 2], [2, 1]],
183 None),
184 LinalgCase("matrix_b_only",
185 array([[1., 2.], [2., 1.]]),
186 None),
187 LinalgCase("hmatrix_a_and_b",
188 matrix([[1., 2.], [2., 1.]]),
189 None),
190 LinalgCase("hmatrix_1x1",
191 np.random.rand(1, 1),
192 None),
193 ]
194
195
196 #
197 # Gufunc test cases
198 #
199
200 GENERALIZED_SQUARE_CASES = []
201 GENERALIZED_NONSQUARE_CASES = []
202 GENERALIZED_HERMITIAN_CASES = []
203
204 for tgt, src in ((GENERALIZED_SQUARE_CASES, SQUARE_CASES),
205 (GENERALIZED_NONSQUARE_CASES, NONSQUARE_CASES),
206 (GENERALIZED_HERMITIAN_CASES, HERMITIAN_CASES)):
207 for case in src:
208 if not isinstance(case.a, np.ndarray):
209 continue
210
211 a = np.array([case.a, 2*case.a, 3*case.a])
212 if case.b is None:
213 b = None
214 else:
215 b = np.array([case.b, 7*case.b, 6*case.b])
216 new_case = LinalgCase(case.name + "_tile3", a, b,
217 case.exception_cls)
218 tgt.append(new_case)
219
220 a = np.array([case.a]*2*3).reshape((3, 2) + case.a.shape)
221 if case.b is None:
222 b = None
223 else:
224 b = np.array([case.b]*2*3).reshape((3, 2) + case.b.shape)
225 new_case = LinalgCase(case.name + "_tile213", a, b,
226 case.exception_cls)
227 tgt.append(new_case)
228
229 #
230 # Generate stride combination variations of the above
231 #
232
233 def _stride_comb_iter(x):
234 """
235 Generate cartesian product of strides for all axes
236 """
237
238 if not isinstance(x, np.ndarray):
239 yield x, "nop"
240 return
241
242 stride_set = [(1,)]*x.ndim
243 stride_set[-1] = (1, 3, -4)
244 if x.ndim > 1:
245 stride_set[-2] = (1, 3, -4)
246 if x.ndim > 2:
247 stride_set[-3] = (1, -4)
248
249 for repeats in itertools.product(*tuple(stride_set)):
250 new_shape = [abs(a*b) for a, b in zip(x.shape, repeats)]
251 slices = tuple([slice(None, None, repeat) for repeat in repeats])
252
253 # new array with different strides, but same data
254 xi = np.empty(new_shape, dtype=x.dtype)
255 xi.view(np.uint32).fill(0xdeadbeef)
256 xi = xi[slices]
257 xi[...] = x
258 xi = xi.view(x.__class__)
259 assert np.all(xi == x)
260 yield xi, "stride_" + "_".join(["%+d" % j for j in repeats])
261
262 # generate also zero strides if possible
263 if x.ndim >= 1 and x.shape[-1] == 1:
264 s = list(x.strides)
265 s[-1] = 0
266 xi = np.lib.stride_tricks.as_strided(x, strides=s)
267 yield xi, "stride_xxx_0"
268 if x.ndim >= 2 and x.shape[-2] == 1:
269 s = list(x.strides)
270 s[-2] = 0
271 xi = np.lib.stride_tricks.as_strided(x, strides=s)
272 yield xi, "stride_xxx_0_x"
273 if x.ndim >= 2 and x.shape[:-2] == (1, 1):
274 s = list(x.strides)
275 s[-1] = 0
276 s[-2] = 0
277 xi = np.lib.stride_tricks.as_strided(x, strides=s)
278 yield xi, "stride_xxx_0_0"
279
280 for src in (SQUARE_CASES,
281 NONSQUARE_CASES,
282 HERMITIAN_CASES,
283 GENERALIZED_SQUARE_CASES,
284 GENERALIZED_NONSQUARE_CASES,
285 GENERALIZED_HERMITIAN_CASES):
286
287 new_cases = []
288 for case in src:
289 for a, a_tag in _stride_comb_iter(case.a):
290 for b, b_tag in _stride_comb_iter(case.b):
291 new_case = LinalgCase(case.name + "_" + a_tag + "_" + b_tag, a, b,
292 exception_cls=case.exception_cls)
293 new_cases.append(new_case)
294 src.extend(new_cases)
295
296
297 #
298 # Test different routines against the above cases
299 #
300
301 def _check_cases(func, cases):
302 for case in cases:
303 try:
304 case.check(func)
305 except Exception:
306 msg = "In test case: %r\n\n" % case
307 msg += traceback.format_exc()
308 raise AssertionError(msg)
309
310 class LinalgTestCase(object):
311 def test_sq_cases(self):
312 _check_cases(self.do, SQUARE_CASES)
313
314
315 class LinalgNonsquareTestCase(object):
316 def test_sq_cases(self):
317 _check_cases(self.do, NONSQUARE_CASES)
318
319
320 class LinalgGeneralizedTestCase(object):
321 @dec.slow
322 def test_generalized_sq_cases(self):
323 _check_cases(self.do, GENERALIZED_SQUARE_CASES)
324
325
326 class LinalgGeneralizedNonsquareTestCase(object):
327 @dec.slow
328 def test_generalized_nonsq_cases(self):
329 _check_cases(self.do, GENERALIZED_NONSQUARE_CASES)
330
331
332 class HermitianTestCase(object):
333 def test_herm_cases(self):
334 _check_cases(self.do, HERMITIAN_CASES)
335
336
337 class HermitianGeneralizedTestCase(object):
338 @dec.slow
339 def test_generalized_herm_cases(self):
340 _check_cases(self.do, GENERALIZED_HERMITIAN_CASES)
341
342
343 def dot_generalized(a, b):
344 a = asarray(a)
345 if a.ndim >= 3:
346 if a.ndim == b.ndim:
347 # matrix x matrix
348 new_shape = a.shape[:-1] + b.shape[-1:]
349 elif a.ndim == b.ndim + 1:
350 # matrix x vector
351 new_shape = a.shape[:-1]
352 else:
353 raise ValueError("Not implemented...")
354 r = np.empty(new_shape, dtype=np.common_type(a, b))
355 for c in itertools.product(*map(range, a.shape[:-2])):
356 r[c] = dot(a[c], b[c])
357 return r
358 else:
359 return dot(a, b)
360
361
362 def identity_like_generalized(a):
363 a = asarray(a)
364 if a.ndim >= 3:
365 r = np.empty(a.shape, dtype=a.dtype)
366 for c in itertools.product(*map(range, a.shape[:-2])):
367 r[c] = identity(a.shape[-2])
368 return r
369 else:
370 return identity(a.shape[0])
371
372
373 class TestSolve(LinalgTestCase, LinalgGeneralizedTestCase):
374 def do(self, a, b):
375 x = linalg.solve(a, b)
376 assert_almost_equal(b, dot_generalized(a, x))
377 assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
378
379 def test_types(self):
380 def check(dtype):
381 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
382 assert_equal(linalg.solve(x, x).dtype, dtype)
383 for dtype in [single, double, csingle, cdouble]:
384 yield check, dtype
385
386 def test_0_size(self):
387 class ArraySubclass(np.ndarray):
388 pass
389 # Test system of 0x0 matrices
390 a = np.arange(8).reshape(2, 2, 2)
391 b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass)
392
393 expected = linalg.solve(a, b)[:, 0:0,:]
394 result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0,:])
395 assert_array_equal(result, expected)
396 assert_(isinstance(result, ArraySubclass))
397
398 # Test errors for non-square and only b's dimension being 0
399 assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b)
400 assert_raises(ValueError, linalg.solve, a, b[:, 0:0,:])
401
402 # Test broadcasting error
403 b = np.arange(6).reshape(1, 3, 2) # broadcasting error
404 assert_raises(ValueError, linalg.solve, a, b)
405 assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
406
407 # Test zero "single equations" with 0x0 matrices.
408 b = np.arange(2).reshape(1, 2).view(ArraySubclass)
409 expected = linalg.solve(a, b)[:, 0:0]
410 result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0])
411 assert_array_equal(result, expected)
412 assert_(isinstance(result, ArraySubclass))
413
414 b = np.arange(3).reshape(1, 3)
415 assert_raises(ValueError, linalg.solve, a, b)
416 assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
417 assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b)
418
419 def test_0_size_k(self):
420 # test zero multiple equation (K=0) case.
421 class ArraySubclass(np.ndarray):
422 pass
423 a = np.arange(4).reshape(1, 2, 2)
424 b = np.arange(6).reshape(3, 2, 1).view(ArraySubclass)
425
426 expected = linalg.solve(a, b)[:,:, 0:0]
427 result = linalg.solve(a, b[:,:, 0:0])
428 assert_array_equal(result, expected)
429 assert_(isinstance(result, ArraySubclass))
430
431 # test both zero.
432 expected = linalg.solve(a, b)[:, 0:0, 0:0]
433 result = linalg.solve(a[:, 0:0, 0:0], b[:,0:0, 0:0])
434 assert_array_equal(result, expected)
435 assert_(isinstance(result, ArraySubclass))
436
437
438 class TestInv(LinalgTestCase, LinalgGeneralizedTestCase):
439 def do(self, a, b):
440 a_inv = linalg.inv(a)
441 assert_almost_equal(dot_generalized(a, a_inv),
442 identity_like_generalized(a))
443 assert_(imply(isinstance(a, matrix), isinstance(a_inv, matrix)))
444
445 def test_types(self):
446 def check(dtype):
447 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
448 assert_equal(linalg.inv(x).dtype, dtype)
449 for dtype in [single, double, csingle, cdouble]:
450 yield check, dtype
451
452 def test_0_size(self):
453 # Check that all kinds of 0-sized arrays work
454 class ArraySubclass(np.ndarray):
455 pass
456 a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
457 res = linalg.inv(a)
458 assert_(res.dtype.type is np.float64)
459 assert_equal(a.shape, res.shape)
460 assert_(isinstance(a, ArraySubclass))
461
462 a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
463 res = linalg.inv(a)
464 assert_(res.dtype.type is np.complex64)
465 assert_equal(a.shape, res.shape)
466
467
468 class TestEigvals(LinalgTestCase, LinalgGeneralizedTestCase):
469 def do(self, a, b):
470 ev = linalg.eigvals(a)
471 evalues, evectors = linalg.eig(a)
472 assert_almost_equal(ev, evalues)
473
474 def test_types(self):
475 def check(dtype):
476 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
477 assert_equal(linalg.eigvals(x).dtype, dtype)
478 x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
479 assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype))
480 for dtype in [single, double, csingle, cdouble]:
481 yield check, dtype
482
483
484 class TestEig(LinalgTestCase, LinalgGeneralizedTestCase):
485 def do(self, a, b):
486 evalues, evectors = linalg.eig(a)
487 assert_allclose(dot_generalized(a, evectors),
488 np.asarray(evectors) * np.asarray(evalues)[...,None,:],
489 rtol=get_rtol(evalues.dtype))
490 assert_(imply(isinstance(a, matrix), isinstance(evectors, matrix)))
491
492 def test_types(self):
493 def check(dtype):
494 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
495 w, v = np.linalg.eig(x)
496 assert_equal(w.dtype, dtype)
497 assert_equal(v.dtype, dtype)
498
499 x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
500 w, v = np.linalg.eig(x)
501 assert_equal(w.dtype, get_complex_dtype(dtype))
502 assert_equal(v.dtype, get_complex_dtype(dtype))
503
504 for dtype in [single, double, csingle, cdouble]:
505 yield check, dtype
506
507
508 class TestSVD(LinalgTestCase, LinalgGeneralizedTestCase):
509 def do(self, a, b):
510 u, s, vt = linalg.svd(a, 0)
511 assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[...,None,:],
512 np.asarray(vt)),
513 rtol=get_rtol(u.dtype))
514 assert_(imply(isinstance(a, matrix), isinstance(u, matrix)))
515 assert_(imply(isinstance(a, matrix), isinstance(vt, matrix)))
516
517 def test_types(self):
518 def check(dtype):
519 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
520 u, s, vh = linalg.svd(x)
521 assert_equal(u.dtype, dtype)
522 assert_equal(s.dtype, get_real_dtype(dtype))
523 assert_equal(vh.dtype, dtype)
524 s = linalg.svd(x, compute_uv=False)
525 assert_equal(s.dtype, get_real_dtype(dtype))
526
527 for dtype in [single, double, csingle, cdouble]:
528 yield check, dtype
529
530
531 class TestCondSVD(LinalgTestCase, LinalgGeneralizedTestCase):
532 def do(self, a, b):
533 c = asarray(a) # a might be a matrix
534 s = linalg.svd(c, compute_uv=False)
535 old_assert_almost_equal(s[0]/s[-1], linalg.cond(a), decimal=5)
536
537
538 class TestCond2(LinalgTestCase):
539 def do(self, a, b):
540 c = asarray(a) # a might be a matrix
541 s = linalg.svd(c, compute_uv=False)
542 old_assert_almost_equal(s[0]/s[-1], linalg.cond(a, 2), decimal=5)
543
544
545 class TestCondInf(object):
546 def test(self):
547 A = array([[1., 0, 0], [0, -2., 0], [0, 0, 3.]])
548 assert_almost_equal(linalg.cond(A, inf), 3.)
549
550
551 class TestPinv(LinalgTestCase):
552 def do(self, a, b):
553 a_ginv = linalg.pinv(a)
554 assert_almost_equal(dot(a, a_ginv), identity(asarray(a).shape[0]))
555 assert_(imply(isinstance(a, matrix), isinstance(a_ginv, matrix)))
556
557
558 class TestDet(LinalgTestCase, LinalgGeneralizedTestCase):
559 def do(self, a, b):
560 d = linalg.det(a)
561 (s, ld) = linalg.slogdet(a)
562 if asarray(a).dtype.type in (single, double):
563 ad = asarray(a).astype(double)
564 else:
565 ad = asarray(a).astype(cdouble)
566 ev = linalg.eigvals(ad)
567 assert_almost_equal(d, multiply.reduce(ev, axis=-1))
568 assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))
569
570 s = np.atleast_1d(s)
571 ld = np.atleast_1d(ld)
572 m = (s != 0)
573 assert_almost_equal(np.abs(s[m]), 1)
574 assert_equal(ld[~m], -inf)
575
576 def test_zero(self):
577 assert_equal(linalg.det([[0.0]]), 0.0)
578 assert_equal(type(linalg.det([[0.0]])), double)
579 assert_equal(linalg.det([[0.0j]]), 0.0)
580 assert_equal(type(linalg.det([[0.0j]])), cdouble)
581
582 assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf))
583 assert_equal(type(linalg.slogdet([[0.0]])[0]), double)
584 assert_equal(type(linalg.slogdet([[0.0]])[1]), double)
585 assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf))
586 assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble)
587 assert_equal(type(linalg.slogdet([[0.0j]])[1]), double)
588
589 def test_types(self):
590 def check(dtype):
591 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
592 assert_equal(np.linalg.det(x).dtype, dtype)
593 ph, s = np.linalg.slogdet(x)
594 assert_equal(s.dtype, get_real_dtype(dtype))
595 assert_equal(ph.dtype, dtype)
596 for dtype in [single, double, csingle, cdouble]:
597 yield check, dtype
598
599
600 class TestLstsq(LinalgTestCase, LinalgNonsquareTestCase):
601 def do(self, a, b):
602 arr = np.asarray(a)
603 m, n = arr.shape
604 u, s, vt = linalg.svd(a, 0)
605 x, residuals, rank, sv = linalg.lstsq(a, b)
606 if m <= n:
607 assert_almost_equal(b, dot(a, x))
608 assert_equal(rank, m)
609 else:
610 assert_equal(rank, n)
611 assert_almost_equal(sv, sv.__array_wrap__(s))
612 if rank == n and m > n:
613 expect_resids = (np.asarray(abs(np.dot(a, x) - b))**2).sum(axis=0)
614 expect_resids = np.asarray(expect_resids)
615 if len(np.asarray(b).shape) == 1:
616 expect_resids.shape = (1,)
617 assert_equal(residuals.shape, expect_resids.shape)
618 else:
619 expect_resids = np.array([]).view(type(x))
620 assert_almost_equal(residuals, expect_resids)
621 assert_(np.issubdtype(residuals.dtype, np.floating))
622 assert_(imply(isinstance(b, matrix), isinstance(x, matrix)))
623 assert_(imply(isinstance(b, matrix), isinstance(residuals, matrix)))
624
625
626 class TestMatrixPower(object):
627 R90 = array([[0, 1], [-1, 0]])
628 Arb22 = array([[4, -7], [-2, 10]])
629 noninv = array([[1, 0], [0, 0]])
630 arbfloat = array([[0.1, 3.2], [1.2, 0.7]])
631
632 large = identity(10)
633 t = large[1,:].copy()
634 large[1,:] = large[0,:]
635 large[0,:] = t
636
637 def test_large_power(self):
638 assert_equal(matrix_power(self.R90, 2**100+2**10+2**5+1), self.R90)
639
640 def test_large_power_trailing_zero(self):
641 assert_equal(matrix_power(self.R90, 2**100+2**10+2**5), identity(2))
642
643 def testip_zero(self):
644 def tz(M):
645 mz = matrix_power(M, 0)
646 assert_equal(mz, identity(M.shape[0]))
647 assert_equal(mz.dtype, M.dtype)
648 for M in [self.Arb22, self.arbfloat, self.large]:
649 yield tz, M
650
651 def testip_one(self):
652 def tz(M):
653 mz = matrix_power(M, 1)
654 assert_equal(mz, M)
655 assert_equal(mz.dtype, M.dtype)
656 for M in [self.Arb22, self.arbfloat, self.large]:
657 yield tz, M
658
659 def testip_two(self):
660 def tz(M):
661 mz = matrix_power(M, 2)
662 assert_equal(mz, dot(M, M))
663 assert_equal(mz.dtype, M.dtype)
664 for M in [self.Arb22, self.arbfloat, self.large]:
665 yield tz, M
666
667 def testip_invert(self):
668 def tz(M):
669 mz = matrix_power(M, -1)
670 assert_almost_equal(identity(M.shape[0]), dot(mz, M))
671 for M in [self.R90, self.Arb22, self.arbfloat, self.large]:
672 yield tz, M
673
674 def test_invert_noninvertible(self):
675 import numpy.linalg
676 assert_raises(numpy.linalg.linalg.LinAlgError,
677 lambda: matrix_power(self.noninv, -1))
678
679
680 class TestBoolPower(object):
681 def test_square(self):
682 A = array([[True, False], [True, True]])
683 assert_equal(matrix_power(A, 2), A)
684
685
686 class TestEigvalsh(HermitianTestCase, HermitianGeneralizedTestCase):
687 def do(self, a, b):
688 # note that eigenvalue arrays must be sorted since
689 # their order isn't guaranteed.
690 ev = linalg.eigvalsh(a, 'L')
691 evalues, evectors = linalg.eig(a)
692 ev.sort(axis=-1)
693 evalues.sort(axis=-1)
694 assert_allclose(ev, evalues,
695 rtol=get_rtol(ev.dtype))
696
697 ev2 = linalg.eigvalsh(a, 'U')
698 ev2.sort(axis=-1)
699 assert_allclose(ev2, evalues,
700 rtol=get_rtol(ev.dtype))
701
702 def test_types(self):
703 def check(dtype):
704 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
705 w = np.linalg.eigvalsh(x)
706 assert_equal(w.dtype, get_real_dtype(dtype))
707 for dtype in [single, double, csingle, cdouble]:
708 yield check, dtype
709
710 def test_invalid(self):
711 x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
712 assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong")
713 assert_raises(ValueError, np.linalg.eigvalsh, x, "lower")
714 assert_raises(ValueError, np.linalg.eigvalsh, x, "upper")
715
716 def test_UPLO(self):
717 Klo = np.array([[0, 0],[1, 0]], dtype=np.double)
718 Kup = np.array([[0, 1],[0, 0]], dtype=np.double)
719 tgt = np.array([-1, 1], dtype=np.double)
720 rtol = get_rtol(np.double)
721
722 # Check default is 'L'
723 w = np.linalg.eigvalsh(Klo)
724 assert_allclose(np.sort(w), tgt, rtol=rtol)
725 # Check 'L'
726 w = np.linalg.eigvalsh(Klo, UPLO='L')
727 assert_allclose(np.sort(w), tgt, rtol=rtol)
728 # Check 'l'
729 w = np.linalg.eigvalsh(Klo, UPLO='l')
730 assert_allclose(np.sort(w), tgt, rtol=rtol)
731 # Check 'U'
732 w = np.linalg.eigvalsh(Kup, UPLO='U')
733 assert_allclose(np.sort(w), tgt, rtol=rtol)
734 # Check 'u'
735 w = np.linalg.eigvalsh(Kup, UPLO='u')
736 assert_allclose(np.sort(w), tgt, rtol=rtol)
737
738
739 class TestEigh(HermitianTestCase, HermitianGeneralizedTestCase):
740 def do(self, a, b):
741 # note that eigenvalue arrays must be sorted since
742 # their order isn't guaranteed.
743 ev, evc = linalg.eigh(a)
744 evalues, evectors = linalg.eig(a)
745 ev.sort(axis=-1)
746 evalues.sort(axis=-1)
747 assert_almost_equal(ev, evalues)
748
749 assert_allclose(dot_generalized(a, evc),
750 np.asarray(ev)[...,None,:] * np.asarray(evc),
751 rtol=get_rtol(ev.dtype))
752
753 ev2, evc2 = linalg.eigh(a, 'U')
754 ev2.sort(axis=-1)
755 assert_almost_equal(ev2, evalues)
756
757 assert_allclose(dot_generalized(a, evc2),
758 np.asarray(ev2)[...,None,:] * np.asarray(evc2),
759 rtol=get_rtol(ev.dtype), err_msg=repr(a))
760
761 def test_types(self):
762 def check(dtype):
763 x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
764 w, v = np.linalg.eigh(x)
765 assert_equal(w.dtype, get_real_dtype(dtype))
766 assert_equal(v.dtype, dtype)
767 for dtype in [single, double, csingle, cdouble]:
768 yield check, dtype
769
770 def test_invalid(self):
771 x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
772 assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
773 assert_raises(ValueError, np.linalg.eigh, x, "lower")
774 assert_raises(ValueError, np.linalg.eigh, x, "upper")
775
776 def test_UPLO(self):
777 Klo = np.array([[0, 0],[1, 0]], dtype=np.double)
778 Kup = np.array([[0, 1],[0, 0]], dtype=np.double)
779 tgt = np.array([-1, 1], dtype=np.double)
780 rtol = get_rtol(np.double)
781
782 # Check default is 'L'
783 w, v = np.linalg.eigh(Klo)
784 assert_allclose(np.sort(w), tgt, rtol=rtol)
785 # Check 'L'
786 w, v = np.linalg.eigh(Klo, UPLO='L')
787 assert_allclose(np.sort(w), tgt, rtol=rtol)
788 # Check 'l'
789 w, v = np.linalg.eigh(Klo, UPLO='l')
790 assert_allclose(np.sort(w), tgt, rtol=rtol)
791 # Check 'U'
792 w, v = np.linalg.eigh(Kup, UPLO='U')
793 assert_allclose(np.sort(w), tgt, rtol=rtol)
794 # Check 'u'
795 w, v = np.linalg.eigh(Kup, UPLO='u')
796 assert_allclose(np.sort(w), tgt, rtol=rtol)
797
798
799 class _TestNorm(object):
800
801 dt = None
802 dec = None
803
804 def test_empty(self):
805 assert_equal(norm([]), 0.0)
806 assert_equal(norm(array([], dtype=self.dt)), 0.0)
807 assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
808
809 def test_vector(self):
810 a = [1, 2, 3, 4]
811 b = [-1, -2, -3, -4]
812 c = [-1, 2, -3, 4]
813
814 def _test(v):
815 np.testing.assert_almost_equal(norm(v), 30**0.5,
816 decimal=self.dec)
817 np.testing.assert_almost_equal(norm(v, inf), 4.0,
818 decimal=self.dec)
819 np.testing.assert_almost_equal(norm(v, -inf), 1.0,
820 decimal=self.dec)
821 np.testing.assert_almost_equal(norm(v, 1), 10.0,
822 decimal=self.dec)
823 np.testing.assert_almost_equal(norm(v, -1), 12.0/25,
824 decimal=self.dec)
825 np.testing.assert_almost_equal(norm(v, 2), 30**0.5,
826 decimal=self.dec)
827 np.testing.assert_almost_equal(norm(v, -2), ((205./144)**-0.5),
828 decimal=self.dec)
829 np.testing.assert_almost_equal(norm(v, 0), 4,
830 decimal=self.dec)
831
832 for v in (a, b, c,):
833 _test(v)
834
835 for v in (array(a, dtype=self.dt), array(b, dtype=self.dt),
836 array(c, dtype=self.dt)):
837 _test(v)
838
839 def test_matrix(self):
840 A = matrix([[1, 3], [5, 7]], dtype=self.dt)
841 assert_almost_equal(norm(A), 84**0.5)
842 assert_almost_equal(norm(A, 'fro'), 84**0.5)
843 assert_almost_equal(norm(A, inf), 12.0)
844 assert_almost_equal(norm(A, -inf), 4.0)
845 assert_almost_equal(norm(A, 1), 10.0)
846 assert_almost_equal(norm(A, -1), 6.0)
847 assert_almost_equal(norm(A, 2), 9.1231056256176615)
848 assert_almost_equal(norm(A, -2), 0.87689437438234041)
849
850 assert_raises(ValueError, norm, A, 'nofro')
851 assert_raises(ValueError, norm, A, -3)
852 assert_raises(ValueError, norm, A, 0)
853
854 def test_axis(self):
855 # Vector norms.
856 # Compare the use of `axis` with computing the norm of each row
857 # or column separately.
858 A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
859 for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
860 expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])]
861 assert_almost_equal(norm(A, ord=order, axis=0), expected0)
862 expected1 = [norm(A[k,:], ord=order) for k in range(A.shape[0])]
863 assert_almost_equal(norm(A, ord=order, axis=1), expected1)
864
865 # Matrix norms.
866 B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
867
868 for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro']:
869 assert_almost_equal(norm(A, ord=order), norm(A, ord=order,
870 axis=(0, 1)))
871
872 n = norm(B, ord=order, axis=(1, 2))
873 expected = [norm(B[k], ord=order) for k in range(B.shape[0])]
874 assert_almost_equal(n, expected)
875
876 n = norm(B, ord=order, axis=(2, 1))
877 expected = [norm(B[k].T, ord=order) for k in range(B.shape[0])]
878 assert_almost_equal(n, expected)
879
880 n = norm(B, ord=order, axis=(0, 2))
881 expected = [norm(B[:, k,:], ord=order) for k in range(B.shape[1])]
882 assert_almost_equal(n, expected)
883
884 n = norm(B, ord=order, axis=(0, 1))
885 expected = [norm(B[:,:, k], ord=order) for k in range(B.shape[2])]
886 assert_almost_equal(n, expected)
887
888 def test_bad_args(self):
889 # Check that bad arguments raise the appropriate exceptions.
890
891 A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
892 B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
893
894 # Using `axis=<integer>` or passing in a 1-D array implies vector
895 # norms are being computed, so also using `ord='fro'` raises a
896 # ValueError.
897 assert_raises(ValueError, norm, A, 'fro', 0)
898 assert_raises(ValueError, norm, [3, 4], 'fro', None)
899
900 # Similarly, norm should raise an exception when ord is any finite
901 # number other than 1, 2, -1 or -2 when computing matrix norms.
902 for order in [0, 3]:
903 assert_raises(ValueError, norm, A, order, None)
904 assert_raises(ValueError, norm, A, order, (0, 1))
905 assert_raises(ValueError, norm, B, order, (1, 2))
906
907 # Invalid axis
908 assert_raises(ValueError, norm, B, None, 3)
909 assert_raises(ValueError, norm, B, None, (2, 3))
910 assert_raises(ValueError, norm, B, None, (0, 1, 2))
911
912 def test_longdouble_norm(self):
913 # Non-regression test: p-norm of longdouble would previously raise
914 # UnboundLocalError.
915 x = np.arange(10, dtype=np.longdouble)
916 old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2)
917
918 def test_intmin(self):
919 # Non-regression test: p-norm of signed integer would previously do
920 # float cast and abs in the wrong order.
921 x = np.array([-2 ** 31], dtype=np.int32)
922 old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5)
923
924 def test_complex_high_ord(self):
925 # gh-4156
926 d = np.empty((2,), dtype=np.clongdouble)
927 d[0] = 6+7j
928 d[1] = -6+7j
929 res = 11.615898132184
930 old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10)
931 d = d.astype(np.complex128)
932 old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9)
933 d = d.astype(np.complex64)
934 old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5)
935
936
937 class TestNormDouble(_TestNorm):
938 dt = np.double
939 dec = 12
940
941
942 class TestNormSingle(_TestNorm):
943 dt = np.float32
944 dec = 6
945
946
947 class TestNormInt64(_TestNorm):
948 dt = np.int64
949 dec = 12
950
951
952 class TestMatrixRank(object):
953 def test_matrix_rank(self):
954 # Full rank matrix
955 yield assert_equal, 4, matrix_rank(np.eye(4))
956 # rank deficient matrix
957 I=np.eye(4); I[-1, -1] = 0.
958 yield assert_equal, matrix_rank(I), 3
959 # All zeros - zero rank
960 yield assert_equal, matrix_rank(np.zeros((4, 4))), 0
961 # 1 dimension - rank 1 unless all 0
962 yield assert_equal, matrix_rank([1, 0, 0, 0]), 1
963 yield assert_equal, matrix_rank(np.zeros((4,))), 0
964 # accepts array-like
965 yield assert_equal, matrix_rank([1]), 1
966 # greater than 2 dimensions raises error
967 yield assert_raises, TypeError, matrix_rank, np.zeros((2, 2, 2))
968 # works on scalar
969 yield assert_equal, matrix_rank(1), 1
970
971
972 def test_reduced_rank():
973 # Test matrices with reduced rank
974 rng = np.random.RandomState(20120714)
975 for i in range(100):
976 # Make a rank deficient matrix
977 X = rng.normal(size=(40, 10))
978 X[:, 0] = X[:, 1] + X[:, 2]
979 # Assert that matrix_rank detected deficiency
980 assert_equal(matrix_rank(X), 9)
981 X[:, 3] = X[:, 4] + X[:, 5]
982 assert_equal(matrix_rank(X), 8)
983
984
985 class TestQR(object):
986
987 def check_qr(self, a):
988 # This test expects the argument `a` to be an ndarray or
989 # a subclass of an ndarray of inexact type.
990 a_type = type(a)
991 a_dtype = a.dtype
992 m, n = a.shape
993 k = min(m, n)
994
995 # mode == 'complete'
996 q, r = linalg.qr(a, mode='complete')
997 assert_(q.dtype == a_dtype)
998 assert_(r.dtype == a_dtype)
999 assert_(isinstance(q, a_type))
1000 assert_(isinstance(r, a_type))
1001 assert_(q.shape == (m, m))
1002 assert_(r.shape == (m, n))
1003 assert_almost_equal(dot(q, r), a)
1004 assert_almost_equal(dot(q.T.conj(), q), np.eye(m))
1005 assert_almost_equal(np.triu(r), r)
1006
1007 # mode == 'reduced'
1008 q1, r1 = linalg.qr(a, mode='reduced')
1009 assert_(q1.dtype == a_dtype)
1010 assert_(r1.dtype == a_dtype)
1011 assert_(isinstance(q1, a_type))
1012 assert_(isinstance(r1, a_type))
1013 assert_(q1.shape == (m, k))
1014 assert_(r1.shape == (k, n))
1015 assert_almost_equal(dot(q1, r1), a)
1016 assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
1017 assert_almost_equal(np.triu(r1), r1)
1018
1019 # mode == 'r'
1020 r2 = linalg.qr(a, mode='r')
1021 assert_(r2.dtype == a_dtype)
1022 assert_(isinstance(r2, a_type))
1023 assert_almost_equal(r2, r1)
1024
1025 def test_qr_empty(self):
1026 a = np.zeros((0, 2))
1027 assert_raises(linalg.LinAlgError, linalg.qr, a)
1028
1029 def test_mode_raw(self):
1030 # The factorization is not unique and varies between libraries,
1031 # so it is not possible to check against known values. Functional
1032 # testing is a possibility, but awaits the exposure of more
1033 # of the functions in lapack_lite. Consequently, this test is
1034 # very limited in scope. Note that the results are in FORTRAN
1035 # order, hence the h arrays are transposed.
1036 a = array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
1037 b = a.astype(np.single)
1038
1039 # Test double
1040 h, tau = linalg.qr(a, mode='raw')
1041 assert_(h.dtype == np.double)
1042 assert_(tau.dtype == np.double)
1043 assert_(h.shape == (2, 3))
1044 assert_(tau.shape == (2,))
1045
1046 h, tau = linalg.qr(a.T, mode='raw')
1047 assert_(h.dtype == np.double)
1048 assert_(tau.dtype == np.double)
1049 assert_(h.shape == (3, 2))
1050 assert_(tau.shape == (2,))
1051
1052 def test_mode_all_but_economic(self):
1053 a = array([[1, 2], [3, 4]])
1054 b = array([[1, 2], [3, 4], [5, 6]])
1055 for dt in "fd":
1056 m1 = a.astype(dt)
1057 m2 = b.astype(dt)
1058 self.check_qr(m1)
1059 self.check_qr(m2)
1060 self.check_qr(m2.T)
1061 self.check_qr(matrix(m1))
1062 for dt in "fd":
1063 m1 = 1 + 1j * a.astype(dt)
1064 m2 = 1 + 1j * b.astype(dt)
1065 self.check_qr(m1)
1066 self.check_qr(m2)
1067 self.check_qr(m2.T)
1068 self.check_qr(matrix(m1))
1069
1070
1071 def test_byteorder_check():
1072 # Byte order check should pass for native order
1073 if sys.byteorder == 'little':
1074 native = '<'
1075 else:
1076 native = '>'
1077
1078 for dtt in (np.float32, np.float64):
1079 arr = np.eye(4, dtype=dtt)
1080 n_arr = arr.newbyteorder(native)
1081 sw_arr = arr.newbyteorder('S').byteswap()
1082 assert_equal(arr.dtype.byteorder, '=')
1083 for routine in (linalg.inv, linalg.det, linalg.pinv):
1084 # Normal call
1085 res = routine(arr)
1086 # Native but not '='
1087 assert_array_equal(res, routine(n_arr))
1088 # Swapped
1089 assert_array_equal(res, routine(sw_arr))
1090
1091
1092 def test_generalized_raise_multiloop():
1093 # It should raise an error even if the error doesn't occur in the
1094 # last iteration of the ufunc inner loop
1095
1096 invertible = np.array([[1, 2], [3, 4]])
1097 non_invertible = np.array([[1, 1], [1, 1]])
1098
1099 x = np.zeros([4, 4, 2, 2])[1::2]
1100 x[...] = invertible
1101 x[0, 0] = non_invertible
1102
1103 assert_raises(np.linalg.LinAlgError, np.linalg.inv, x)
1104
1105 def test_xerbla_override():
1106 # Check that our xerbla has been successfully linked in. If it is not,
1107 # the default xerbla routine is called, which prints a message to stdout
1108 # and may, or may not, abort the process depending on the LAPACK package.
1109 from nose import SkipTest
1110
1111 try:
1112 pid = os.fork()
1113 except (OSError, AttributeError):
1114 # fork failed, or not running on POSIX
1115 raise SkipTest("Not POSIX or fork failed.")
1116
1117 if pid == 0:
1118 # child; close i/o file handles
1119 os.close(1)
1120 os.close(0)
1121 # Avoid producing core files.
1122 import resource
1123 resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
1124 # These calls may abort.
1125 try:
1126 np.linalg.lapack_lite.xerbla()
1127 except ValueError:
1128 pass
1129 except:
1130 os._exit(os.EX_CONFIG)
1131
1132 try:
1133 a = np.array([[1.]])
1134 np.linalg.lapack_lite.dorgqr(
1135 1, 1, 1, a,
1136 0, # <- invalid value
1137 a, a, 0, 0)
1138 except ValueError as e:
1139 if "DORGQR parameter number 5" in str(e):
1140 # success
1141 os._exit(os.EX_OK)
1142
1143 # Did not abort, but our xerbla was not linked in.
1144 os._exit(os.EX_CONFIG)
1145 else:
1146 # parent
1147 pid, status = os.wait()
1148 if os.WEXITSTATUS(status) != os.EX_OK or os.WIFSIGNALED(status):
1149 raise SkipTest('Numpy xerbla not linked in.')
1150
1151
1152 if __name__ == "__main__":
1153 run_module_suite()