/scipy/linalg/decomp.py

https://github.com/satyamsatyarthi/scipy · Python · 857 lines · 615 code · 32 blank · 210 comment · 86 complexity · 7ef8084d1e6725d30cdbb3464931eb50 MD5 · raw file

  1. #
  2. # Author: Pearu Peterson, March 2002
  3. #
  4. # additions by Travis Oliphant, March 2002
  5. # additions by Eric Jones, June 2002
  6. # additions by Johannes Loehnert, June 2006
  7. # additions by Bart Vandereycken, June 2006
  8. # additions by Andrew D Straw, May 2007
  9. # additions by Tiziano Zito, November 2008
  10. #
  11. # April 2010: Functions for LU, QR, SVD, Schur and Cholesky decompositions were
  12. # moved to their own files. Still in this file are functions for eigenstuff
  13. # and for the Hessenberg form.
  14. from __future__ import division, print_function, absolute_import
  15. __all__ = ['eig','eigh','eig_banded','eigvals','eigvalsh', 'eigvals_banded',
  16. 'hessenberg']
  17. import numpy
  18. from numpy import array, asarray_chkfinite, asarray, diag, zeros, ones, \
  19. isfinite, inexact, nonzero, iscomplexobj, cast, flatnonzero, conj
  20. # Local imports
  21. from scipy.lib.six import xrange
  22. from scipy.linalg import calc_lwork
  23. from .misc import LinAlgError, _datacopied, norm
  24. from .lapack import get_lapack_funcs
  25. from .blas import get_blas_funcs
  26. _I = cast['F'](1j)
  27. def _make_complex_eigvecs(w, vin, dtype):
  28. """
  29. Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output
  30. """
  31. # - see LAPACK man page DGGEV at ALPHAI
  32. v = numpy.array(vin, dtype=dtype)
  33. m = (w.imag > 0)
  34. m[:-1] |= (w.imag[1:] < 0) # workaround for LAPACK bug, cf. ticket #709
  35. for i in flatnonzero(m):
  36. v.imag[:,i] = vin[:,i+1]
  37. conj(v[:,i], v[:,i+1])
  38. return v
  39. def _geneig(a1, b1, left, right, overwrite_a, overwrite_b):
  40. ggev, = get_lapack_funcs(('ggev',), (a1, b1))
  41. cvl, cvr = left, right
  42. res = ggev(a1, b1, lwork=-1)
  43. lwork = res[-2][0].real.astype(numpy.int)
  44. if ggev.typecode in 'cz':
  45. alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,
  46. overwrite_a, overwrite_b)
  47. w = alpha / beta
  48. else:
  49. alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,
  50. overwrite_a,overwrite_b)
  51. w = (alphar + _I * alphai) / beta
  52. if info < 0:
  53. raise ValueError('illegal value in %d-th argument of internal ggev'
  54. % -info)
  55. if info > 0:
  56. raise LinAlgError("generalized eig algorithm did not converge (info=%d)"
  57. % info)
  58. only_real = numpy.logical_and.reduce(numpy.equal(w.imag, 0.0))
  59. if not (ggev.typecode in 'cz' or only_real):
  60. t = w.dtype.char
  61. if left:
  62. vl = _make_complex_eigvecs(w, vl, t)
  63. if right:
  64. vr = _make_complex_eigvecs(w, vr, t)
  65. # the eigenvectors returned by the lapack function are NOT normalized
  66. for i in xrange(vr.shape[0]):
  67. if right:
  68. vr[:, i] /= norm(vr[:, i])
  69. if left:
  70. vl[:, i] /= norm(vl[:, i])
  71. if not (left or right):
  72. return w
  73. if left:
  74. if right:
  75. return w, vl, vr
  76. return w, vl
  77. return w, vr
  78. def eig(a, b=None, left=False, right=True, overwrite_a=False,
  79. overwrite_b=False, check_finite=True):
  80. """
  81. Solve an ordinary or generalized eigenvalue problem of a square matrix.
  82. Find eigenvalues w and right or left eigenvectors of a general matrix::
  83. a vr[:,i] = w[i] b vr[:,i]
  84. a.H vl[:,i] = w[i].conj() b.H vl[:,i]
  85. where ``.H`` is the Hermitian conjugation.
  86. Parameters
  87. ----------
  88. a : (M, M) array_like
  89. A complex or real matrix whose eigenvalues and eigenvectors
  90. will be computed.
  91. b : (M, M) array_like, optional
  92. Right-hand side matrix in a generalized eigenvalue problem.
  93. Default is None, identity matrix is assumed.
  94. left : bool, optional
  95. Whether to calculate and return left eigenvectors. Default is False.
  96. right : bool, optional
  97. Whether to calculate and return right eigenvectors. Default is True.
  98. overwrite_a : bool, optional
  99. Whether to overwrite `a`; may improve performance. Default is False.
  100. overwrite_b : bool, optional
  101. Whether to overwrite `b`; may improve performance. Default is False.
  102. check_finite : boolean, optional
  103. Whether to check that the input matrices contain only finite numbers.
  104. Disabling may give a performance gain, but may result in problems
  105. (crashes, non-termination) if the inputs do contain infinities or NaNs.
  106. Returns
  107. -------
  108. w : (M,) double or complex ndarray
  109. The eigenvalues, each repeated according to its multiplicity.
  110. vl : (M, M) double or complex ndarray
  111. The normalized left eigenvector corresponding to the eigenvalue
  112. ``w[i]`` is the column v[:,i]. Only returned if ``left=True``.
  113. vr : (M, M) double or complex ndarray
  114. The normalized right eigenvector corresponding to the eigenvalue
  115. ``w[i]`` is the column ``vr[:,i]``. Only returned if ``right=True``.
  116. Raises
  117. ------
  118. LinAlgError
  119. If eigenvalue computation does not converge.
  120. See Also
  121. --------
  122. eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.
  123. """
  124. if check_finite:
  125. a1 = asarray_chkfinite(a)
  126. else:
  127. a1 = asarray(a)
  128. if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
  129. raise ValueError('expected square matrix')
  130. overwrite_a = overwrite_a or (_datacopied(a1, a))
  131. if b is not None:
  132. if check_finite:
  133. b1 = asarray_chkfinite(b)
  134. else:
  135. b1 = asarray(b)
  136. overwrite_b = overwrite_b or _datacopied(b1, b)
  137. if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
  138. raise ValueError('expected square matrix')
  139. if b1.shape != a1.shape:
  140. raise ValueError('a and b must have the same shape')
  141. return _geneig(a1, b1, left, right, overwrite_a, overwrite_b)
  142. geev, = get_lapack_funcs(('geev',), (a1,))
  143. compute_vl, compute_vr = left, right
  144. lwork = calc_lwork.geev(geev.typecode, a1.shape[0],
  145. compute_vl, compute_vr)[1]
  146. if geev.typecode in 'cz':
  147. w, vl, vr, info = geev(a1, lwork=lwork,
  148. compute_vl=compute_vl,
  149. compute_vr=compute_vr,
  150. overwrite_a=overwrite_a)
  151. else:
  152. wr, wi, vl, vr, info = geev(a1, lwork=lwork,
  153. compute_vl=compute_vl,
  154. compute_vr=compute_vr,
  155. overwrite_a=overwrite_a)
  156. t = {'f':'F','d':'D'}[wr.dtype.char]
  157. w = wr + _I * wi
  158. if info < 0:
  159. raise ValueError('illegal value in %d-th argument of internal geev'
  160. % -info)
  161. if info > 0:
  162. raise LinAlgError("eig algorithm did not converge (only eigenvalues "
  163. "with order >= %d have converged)" % info)
  164. only_real = numpy.logical_and.reduce(numpy.equal(w.imag, 0.0))
  165. if not (geev.typecode in 'cz' or only_real):
  166. t = w.dtype.char
  167. if left:
  168. vl = _make_complex_eigvecs(w, vl, t)
  169. if right:
  170. vr = _make_complex_eigvecs(w, vr, t)
  171. if not (left or right):
  172. return w
  173. if left:
  174. if right:
  175. return w, vl, vr
  176. return w, vl
  177. return w, vr
  178. def eigh(a, b=None, lower=True, eigvals_only=False, overwrite_a=False,
  179. overwrite_b=False, turbo=True, eigvals=None, type=1,
  180. check_finite=True):
  181. """
  182. Solve an ordinary or generalized eigenvalue problem for a complex
  183. Hermitian or real symmetric matrix.
  184. Find eigenvalues w and optionally eigenvectors v of matrix `a`, where
  185. `b` is positive definite::
  186. a v[:,i] = w[i] b v[:,i]
  187. v[i,:].conj() a v[:,i] = w[i]
  188. v[i,:].conj() b v[:,i] = 1
  189. Parameters
  190. ----------
  191. a : (M, M) array_like
  192. A complex Hermitian or real symmetric matrix whose eigenvalues and
  193. eigenvectors will be computed.
  194. b : (M, M) array_like, optional
  195. A complex Hermitian or real symmetric definite positive matrix in.
  196. If omitted, identity matrix is assumed.
  197. lower : bool, optional
  198. Whether the pertinent array data is taken from the lower or upper
  199. triangle of `a`. (Default: lower)
  200. eigvals_only : bool, optional
  201. Whether to calculate only eigenvalues and no eigenvectors.
  202. (Default: both are calculated)
  203. turbo : bool, optional
  204. Use divide and conquer algorithm (faster but expensive in memory,
  205. only for generalized eigenvalue problem and if eigvals=None)
  206. eigvals : tuple (lo, hi), optional
  207. Indexes of the smallest and largest (in ascending order) eigenvalues
  208. and corresponding eigenvectors to be returned: 0 <= lo <= hi <= M-1.
  209. If omitted, all eigenvalues and eigenvectors are returned.
  210. type : int, optional
  211. Specifies the problem type to be solved:
  212. type = 1: a v[:,i] = w[i] b v[:,i]
  213. type = 2: a b v[:,i] = w[i] v[:,i]
  214. type = 3: b a v[:,i] = w[i] v[:,i]
  215. overwrite_a : bool, optional
  216. Whether to overwrite data in `a` (may improve performance)
  217. overwrite_b : bool, optional
  218. Whether to overwrite data in `b` (may improve performance)
  219. check_finite : boolean, optional
  220. Whether to check that the input matrices contain only finite numbers.
  221. Disabling may give a performance gain, but may result in problems
  222. (crashes, non-termination) if the inputs do contain infinities or NaNs.
  223. Returns
  224. -------
  225. w : (N,) float ndarray
  226. The N (1<=N<=M) selected eigenvalues, in ascending order, each
  227. repeated according to its multiplicity.
  228. v : (M, N) complex ndarray
  229. (if eigvals_only == False)
  230. The normalized selected eigenvector corresponding to the
  231. eigenvalue w[i] is the column v[:,i].
  232. Normalization:
  233. type 1 and 3: v.conj() a v = w
  234. type 2: inv(v).conj() a inv(v) = w
  235. type = 1 or 2: v.conj() b v = I
  236. type = 3: v.conj() inv(b) v = I
  237. Raises
  238. ------
  239. LinAlgError :
  240. If eigenvalue computation does not converge,
  241. an error occurred, or b matrix is not definite positive. Note that
  242. if input matrices are not symmetric or hermitian, no error is reported
  243. but results will be wrong.
  244. See Also
  245. --------
  246. eig : eigenvalues and right eigenvectors for non-symmetric arrays
  247. """
  248. if check_finite:
  249. a1 = asarray_chkfinite(a)
  250. else:
  251. a1 = asarray(a)
  252. if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
  253. raise ValueError('expected square matrix')
  254. overwrite_a = overwrite_a or (_datacopied(a1, a))
  255. if iscomplexobj(a1):
  256. cplx = True
  257. else:
  258. cplx = False
  259. if b is not None:
  260. if check_finite:
  261. b1 = asarray_chkfinite(b)
  262. else:
  263. b1 = asarray(b)
  264. overwrite_b = overwrite_b or _datacopied(b1, b)
  265. if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
  266. raise ValueError('expected square matrix')
  267. if b1.shape != a1.shape:
  268. raise ValueError("wrong b dimensions %s, should "
  269. "be %s" % (str(b1.shape), str(a1.shape)))
  270. if iscomplexobj(b1):
  271. cplx = True
  272. else:
  273. cplx = cplx or False
  274. else:
  275. b1 = None
  276. # Set job for fortran routines
  277. _job = (eigvals_only and 'N') or 'V'
  278. # port eigenvalue range from python to fortran convention
  279. if eigvals is not None:
  280. lo, hi = eigvals
  281. if lo < 0 or hi >= a1.shape[0]:
  282. raise ValueError('The eigenvalue range specified is not valid.\n'
  283. 'Valid range is [%s,%s]' % (0, a1.shape[0]-1))
  284. lo += 1
  285. hi += 1
  286. eigvals = (lo, hi)
  287. # set lower
  288. if lower:
  289. uplo = 'L'
  290. else:
  291. uplo = 'U'
  292. # fix prefix for lapack routines
  293. if cplx:
  294. pfx = 'he'
  295. else:
  296. pfx = 'sy'
  297. # Standard Eigenvalue Problem
  298. # Use '*evr' routines
  299. # FIXME: implement calculation of optimal lwork
  300. # for all lapack routines
  301. if b1 is None:
  302. (evr,) = get_lapack_funcs((pfx+'evr',), (a1,))
  303. if eigvals is None:
  304. w, v, info = evr(a1, uplo=uplo, jobz=_job, range="A", il=1,
  305. iu=a1.shape[0], overwrite_a=overwrite_a)
  306. else:
  307. (lo, hi) = eigvals
  308. w_tot, v, info = evr(a1, uplo=uplo, jobz=_job, range="I",
  309. il=lo, iu=hi, overwrite_a=overwrite_a)
  310. w = w_tot[0:hi-lo+1]
  311. # Generalized Eigenvalue Problem
  312. else:
  313. # Use '*gvx' routines if range is specified
  314. if eigvals is not None:
  315. (gvx,) = get_lapack_funcs((pfx+'gvx',), (a1,b1))
  316. (lo, hi) = eigvals
  317. w_tot, v, ifail, info = gvx(a1, b1, uplo=uplo, iu=hi,
  318. itype=type,jobz=_job, il=lo,
  319. overwrite_a=overwrite_a,
  320. overwrite_b=overwrite_b)
  321. w = w_tot[0:hi-lo+1]
  322. # Use '*gvd' routine if turbo is on and no eigvals are specified
  323. elif turbo:
  324. (gvd,) = get_lapack_funcs((pfx+'gvd',), (a1,b1))
  325. v, w, info = gvd(a1, b1, uplo=uplo, itype=type, jobz=_job,
  326. overwrite_a=overwrite_a,
  327. overwrite_b=overwrite_b)
  328. # Use '*gv' routine if turbo is off and no eigvals are specified
  329. else:
  330. (gv,) = get_lapack_funcs((pfx+'gv',), (a1,b1))
  331. v, w, info = gv(a1, b1, uplo=uplo, itype=type, jobz=_job,
  332. overwrite_a=overwrite_a,
  333. overwrite_b=overwrite_b)
  334. # Check if we had a successful exit
  335. if info == 0:
  336. if eigvals_only:
  337. return w
  338. else:
  339. return w, v
  340. elif info < 0:
  341. raise LinAlgError("illegal value in %i-th argument of internal"
  342. " fortran routine." % (-info))
  343. elif info > 0 and b1 is None:
  344. raise LinAlgError("unrecoverable internal error.")
  345. # The algorithm failed to converge.
  346. elif info > 0 and info <= b1.shape[0]:
  347. if eigvals is not None:
  348. raise LinAlgError("the eigenvectors %s failed to"
  349. " converge." % nonzero(ifail)-1)
  350. else:
  351. raise LinAlgError("internal fortran routine failed to converge: "
  352. "%i off-diagonal elements of an "
  353. "intermediate tridiagonal form did not converge"
  354. " to zero." % info)
  355. # This occurs when b is not positive definite
  356. else:
  357. raise LinAlgError("the leading minor of order %i"
  358. " of 'b' is not positive definite. The"
  359. " factorization of 'b' could not be completed"
  360. " and no eigenvalues or eigenvectors were"
  361. " computed." % (info-b1.shape[0]))
  362. def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
  363. select='a', select_range=None, max_ev=0, check_finite=True):
  364. """
  365. Solve real symmetric or complex hermitian band matrix eigenvalue problem.
  366. Find eigenvalues w and optionally right eigenvectors v of a::
  367. a v[:,i] = w[i] v[:,i]
  368. v.H v = identity
  369. The matrix a is stored in a_band either in lower diagonal or upper
  370. diagonal ordered form:
  371. a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)
  372. a_band[ i - j, j] == a[i,j] (if lower form; i >= j)
  373. where u is the number of bands above the diagonal.
  374. Example of a_band (shape of a is (6,6), u=2)::
  375. upper form:
  376. * * a02 a13 a24 a35
  377. * a01 a12 a23 a34 a45
  378. a00 a11 a22 a33 a44 a55
  379. lower form:
  380. a00 a11 a22 a33 a44 a55
  381. a10 a21 a32 a43 a54 *
  382. a20 a31 a42 a53 * *
  383. Cells marked with * are not used.
  384. Parameters
  385. ----------
  386. a_band : (u+1, M) array_like
  387. The bands of the M by M matrix a.
  388. lower : bool, optional
  389. Is the matrix in the lower form. (Default is upper form)
  390. eigvals_only : bool, optional
  391. Compute only the eigenvalues and no eigenvectors.
  392. (Default: calculate also eigenvectors)
  393. overwrite_a_band : bool, optional
  394. Discard data in a_band (may enhance performance)
  395. select : {'a', 'v', 'i'}, optional
  396. Which eigenvalues to calculate
  397. ====== ========================================
  398. select calculated
  399. ====== ========================================
  400. 'a' All eigenvalues
  401. 'v' Eigenvalues in the interval (min, max]
  402. 'i' Eigenvalues with indices min <= i <= max
  403. ====== ========================================
  404. select_range : (min, max), optional
  405. Range of selected eigenvalues
  406. max_ev : int, optional
  407. For select=='v', maximum number of eigenvalues expected.
  408. For other values of select, has no meaning.
  409. In doubt, leave this parameter untouched.
  410. check_finite : boolean, optional
  411. Whether to check that the input matrix contains only finite numbers.
  412. Disabling may give a performance gain, but may result in problems
  413. (crashes, non-termination) if the inputs do contain infinities or NaNs.
  414. Returns
  415. -------
  416. w : (M,) ndarray
  417. The eigenvalues, in ascending order, each repeated according to its
  418. multiplicity.
  419. v : (M, M) float or complex ndarray
  420. The normalized eigenvector corresponding to the eigenvalue w[i] is
  421. the column v[:,i].
  422. Raises LinAlgError if eigenvalue computation does not converge
  423. """
  424. if eigvals_only or overwrite_a_band:
  425. if check_finite:
  426. a1 = asarray_chkfinite(a_band)
  427. else:
  428. a1 = asarray(a_band)
  429. overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))
  430. else:
  431. a1 = array(a_band)
  432. if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():
  433. raise ValueError("array must not contain infs or NaNs")
  434. overwrite_a_band = 1
  435. if len(a1.shape) != 2:
  436. raise ValueError('expected two-dimensional array')
  437. if select.lower() not in [0, 1, 2, 'a', 'v', 'i', 'all', 'value', 'index']:
  438. raise ValueError('invalid argument for select')
  439. if select.lower() in [0, 'a', 'all']:
  440. if a1.dtype.char in 'GFD':
  441. bevd, = get_lapack_funcs(('hbevd',), (a1,))
  442. # FIXME: implement this somewhen, for now go with builtin values
  443. # FIXME: calc optimal lwork by calling ?hbevd(lwork=-1)
  444. # or by using calc_lwork.f ???
  445. # lwork = calc_lwork.hbevd(bevd.typecode, a1.shape[0], lower)
  446. internal_name = 'hbevd'
  447. else: # a1.dtype.char in 'fd':
  448. bevd, = get_lapack_funcs(('sbevd',), (a1,))
  449. # FIXME: implement this somewhen, for now go with builtin values
  450. # see above
  451. # lwork = calc_lwork.sbevd(bevd.typecode, a1.shape[0], lower)
  452. internal_name = 'sbevd'
  453. w,v,info = bevd(a1, compute_v=not eigvals_only,
  454. lower=lower,
  455. overwrite_ab=overwrite_a_band)
  456. if select.lower() in [1, 2, 'i', 'v', 'index', 'value']:
  457. # calculate certain range only
  458. if select.lower() in [2, 'i', 'index']:
  459. select = 2
  460. vl, vu, il, iu = 0.0, 0.0, min(select_range), max(select_range)
  461. if min(il, iu) < 0 or max(il, iu) >= a1.shape[1]:
  462. raise ValueError('select_range out of bounds')
  463. max_ev = iu - il + 1
  464. else: # 1, 'v', 'value'
  465. select = 1
  466. vl, vu, il, iu = min(select_range), max(select_range), 0, 0
  467. if max_ev == 0:
  468. max_ev = a_band.shape[1]
  469. if eigvals_only:
  470. max_ev = 1
  471. # calculate optimal abstol for dsbevx (see manpage)
  472. if a1.dtype.char in 'fF': # single precision
  473. lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),))
  474. else:
  475. lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),))
  476. abstol = 2 * lamch('s')
  477. if a1.dtype.char in 'GFD':
  478. bevx, = get_lapack_funcs(('hbevx',), (a1,))
  479. internal_name = 'hbevx'
  480. else: # a1.dtype.char in 'gfd'
  481. bevx, = get_lapack_funcs(('sbevx',), (a1,))
  482. internal_name = 'sbevx'
  483. # il+1, iu+1: translate python indexing (0 ... N-1) into Fortran
  484. # indexing (1 ... N)
  485. w, v, m, ifail, info = bevx(a1, vl, vu, il+1, iu+1,
  486. compute_v=not eigvals_only,
  487. mmax=max_ev,
  488. range=select, lower=lower,
  489. overwrite_ab=overwrite_a_band,
  490. abstol=abstol)
  491. # crop off w and v
  492. w = w[:m]
  493. if not eigvals_only:
  494. v = v[:, :m]
  495. if info < 0:
  496. raise ValueError('illegal value in %d-th argument of internal %s'
  497. % (-info, internal_name))
  498. if info > 0:
  499. raise LinAlgError("eig algorithm did not converge")
  500. if eigvals_only:
  501. return w
  502. return w, v
  503. def eigvals(a, b=None, overwrite_a=False, check_finite=True):
  504. """
  505. Compute eigenvalues from an ordinary or generalized eigenvalue problem.
  506. Find eigenvalues of a general matrix::
  507. a vr[:,i] = w[i] b vr[:,i]
  508. Parameters
  509. ----------
  510. a : (M, M) array_like
  511. A complex or real matrix whose eigenvalues and eigenvectors
  512. will be computed.
  513. b : (M, M) array_like, optional
  514. Right-hand side matrix in a generalized eigenvalue problem.
  515. If omitted, identity matrix is assumed.
  516. overwrite_a : boolean, optional
  517. Whether to overwrite data in a (may improve performance)
  518. check_finite : boolean, optional
  519. Whether to check that the input matrices contain only finite numbers.
  520. Disabling may give a performance gain, but may result in problems
  521. (crashes, non-termination) if the inputs do contain infinities or NaNs.
  522. Returns
  523. -------
  524. w : (M,) double or complex ndarray
  525. The eigenvalues, each repeated according to its multiplicity,
  526. but not in any specific order.
  527. Raises
  528. ------
  529. LinAlgError
  530. If eigenvalue computation does not converge
  531. See Also
  532. --------
  533. eigvalsh : eigenvalues of symmetric or Hermitian arrays,
  534. eig : eigenvalues and right eigenvectors of general arrays.
  535. eigh : eigenvalues and eigenvectors of symmetric/Hermitian arrays.
  536. """
  537. return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a,
  538. check_finite=check_finite)
  539. def eigvalsh(a, b=None, lower=True, overwrite_a=False,
  540. overwrite_b=False, turbo=True, eigvals=None, type=1,
  541. check_finite=True):
  542. """
  543. Solve an ordinary or generalized eigenvalue problem for a complex
  544. Hermitian or real symmetric matrix.
  545. Find eigenvalues w of matrix a, where b is positive definite::
  546. a v[:,i] = w[i] b v[:,i]
  547. v[i,:].conj() a v[:,i] = w[i]
  548. v[i,:].conj() b v[:,i] = 1
  549. Parameters
  550. ----------
  551. a : (M, M) array_like
  552. A complex Hermitian or real symmetric matrix whose eigenvalues and
  553. eigenvectors will be computed.
  554. b : (M, M) array_like, optional
  555. A complex Hermitian or real symmetric definite positive matrix in.
  556. If omitted, identity matrix is assumed.
  557. lower : bool, optional
  558. Whether the pertinent array data is taken from the lower or upper
  559. triangle of `a`. (Default: lower)
  560. turbo : bool, optional
  561. Use divide and conquer algorithm (faster but expensive in memory,
  562. only for generalized eigenvalue problem and if eigvals=None)
  563. eigvals : tuple (lo, hi), optional
  564. Indexes of the smallest and largest (in ascending order) eigenvalues
  565. and corresponding eigenvectors to be returned: 0 <= lo < hi <= M-1.
  566. If omitted, all eigenvalues and eigenvectors are returned.
  567. type : integer, optional
  568. Specifies the problem type to be solved:
  569. type = 1: a v[:,i] = w[i] b v[:,i]
  570. type = 2: a b v[:,i] = w[i] v[:,i]
  571. type = 3: b a v[:,i] = w[i] v[:,i]
  572. overwrite_a : bool, optional
  573. Whether to overwrite data in `a` (may improve performance)
  574. overwrite_b : bool, optional
  575. Whether to overwrite data in `b` (may improve performance)
  576. check_finite : boolean, optional
  577. Whether to check that the input matrices contain only finite numbers.
  578. Disabling may give a performance gain, but may result in problems
  579. (crashes, non-termination) if the inputs do contain infinities or NaNs.
  580. Returns
  581. -------
  582. w : (N,) float ndarray
  583. The N (1<=N<=M) selected eigenvalues, in ascending order, each
  584. repeated according to its multiplicity.
  585. Raises
  586. ------
  587. LinAlgError :
  588. If eigenvalue computation does not converge,
  589. an error occurred, or b matrix is not definite positive. Note that
  590. if input matrices are not symmetric or hermitian, no error is reported
  591. but results will be wrong.
  592. See Also
  593. --------
  594. eigvals : eigenvalues of general arrays
  595. eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
  596. eig : eigenvalues and right eigenvectors for non-symmetric arrays
  597. """
  598. return eigh(a, b=b, lower=lower, eigvals_only=True,
  599. overwrite_a=overwrite_a, overwrite_b=overwrite_b,
  600. turbo=turbo, eigvals=eigvals, type=type,
  601. check_finite=check_finite)
  602. def eigvals_banded(a_band, lower=False, overwrite_a_band=False,
  603. select='a', select_range=None, check_finite=True):
  604. """
  605. Solve real symmetric or complex hermitian band matrix eigenvalue problem.
  606. Find eigenvalues w of a::
  607. a v[:,i] = w[i] v[:,i]
  608. v.H v = identity
  609. The matrix a is stored in a_band either in lower diagonal or upper
  610. diagonal ordered form:
  611. a_band[u + i - j, j] == a[i,j] (if upper form; i <= j)
  612. a_band[ i - j, j] == a[i,j] (if lower form; i >= j)
  613. where u is the number of bands above the diagonal.
  614. Example of a_band (shape of a is (6,6), u=2)::
  615. upper form:
  616. * * a02 a13 a24 a35
  617. * a01 a12 a23 a34 a45
  618. a00 a11 a22 a33 a44 a55
  619. lower form:
  620. a00 a11 a22 a33 a44 a55
  621. a10 a21 a32 a43 a54 *
  622. a20 a31 a42 a53 * *
  623. Cells marked with * are not used.
  624. Parameters
  625. ----------
  626. a_band : (u+1, M) array_like
  627. The bands of the M by M matrix a.
  628. lower : boolean
  629. Is the matrix in the lower form. (Default is upper form)
  630. overwrite_a_band:
  631. Discard data in a_band (may enhance performance)
  632. select : {'a', 'v', 'i'}
  633. Which eigenvalues to calculate
  634. ====== ========================================
  635. select calculated
  636. ====== ========================================
  637. 'a' All eigenvalues
  638. 'v' Eigenvalues in the interval (min, max]
  639. 'i' Eigenvalues with indices min <= i <= max
  640. ====== ========================================
  641. select_range : (min, max)
  642. Range of selected eigenvalues
  643. check_finite : boolean, optional
  644. Whether to check that the input matrix contains only finite numbers.
  645. Disabling may give a performance gain, but may result in problems
  646. (crashes, non-termination) if the inputs do contain infinities or NaNs.
  647. Returns
  648. -------
  649. w : (M,) ndarray
  650. The eigenvalues, in ascending order, each repeated according to its
  651. multiplicity.
  652. Raises LinAlgError if eigenvalue computation does not converge
  653. See Also
  654. --------
  655. eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
  656. band matrices
  657. eigvals : eigenvalues of general arrays
  658. eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
  659. eig : eigenvalues and right eigenvectors for non-symmetric arrays
  660. """
  661. return eig_banded(a_band, lower=lower, eigvals_only=1,
  662. overwrite_a_band=overwrite_a_band, select=select,
  663. select_range=select_range, check_finite=check_finite)
  664. _double_precision = ['i','l','d']
  665. def hessenberg(a, calc_q=False, overwrite_a=False, check_finite=True):
  666. """
  667. Compute Hessenberg form of a matrix.
  668. The Hessenberg decomposition is::
  669. A = Q H Q^H
  670. where `Q` is unitary/orthogonal and `H` has only zero elements below
  671. the first sub-diagonal.
  672. Parameters
  673. ----------
  674. a : (M, M) array_like
  675. Matrix to bring into Hessenberg form.
  676. calc_q : bool, optional
  677. Whether to compute the transformation matrix. Default is False.
  678. overwrite_a : bool, optional
  679. Whether to overwrite `a`; may improve performance.
  680. Default is False.
  681. check_finite : boolean, optional
  682. Whether to check that the input matrix contains only finite numbers.
  683. Disabling may give a performance gain, but may result in problems
  684. (crashes, non-termination) if the inputs do contain infinities or NaNs.
  685. Returns
  686. -------
  687. H : (M, M) ndarray
  688. Hessenberg form of `a`.
  689. Q : (M, M) ndarray
  690. Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``.
  691. Only returned if ``calc_q=True``.
  692. """
  693. if check_finite:
  694. a1 = asarray_chkfinite(a)
  695. else:
  696. a1 = asarray(a)
  697. if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
  698. raise ValueError('expected square matrix')
  699. overwrite_a = overwrite_a or (_datacopied(a1, a))
  700. gehrd,gebal = get_lapack_funcs(('gehrd','gebal'), (a1,))
  701. ba, lo, hi, pivscale, info = gebal(a1, permute=0, overwrite_a=overwrite_a)
  702. if info < 0:
  703. raise ValueError('illegal value in %d-th argument of internal gebal '
  704. '(hessenberg)' % -info)
  705. n = len(a1)
  706. lwork = calc_lwork.gehrd(gehrd.typecode, n, lo, hi)
  707. hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
  708. if info < 0:
  709. raise ValueError('illegal value in %d-th argument of internal gehrd '
  710. '(hessenberg)' % -info)
  711. if not calc_q:
  712. for i in range(lo, hi):
  713. hq[i+2:hi+1, i] = 0.0
  714. return hq
  715. # XXX: Use ORGHR routines to compute q.
  716. typecode = hq.dtype
  717. ger,gemm = get_blas_funcs(('ger','gemm'), dtype=typecode)
  718. q = None
  719. for i in range(lo, hi):
  720. if tau[i] == 0.0:
  721. continue
  722. v = zeros(n, dtype=typecode)
  723. v[i+1] = 1.0
  724. v[i+2:hi+1] = hq[i+2:hi+1, i]
  725. hq[i+2:hi+1, i] = 0.0
  726. h = ger(-tau[i], v, v,a=diag(ones(n, dtype=typecode)), overwrite_a=1)
  727. if q is None:
  728. q = h
  729. else:
  730. q = gemm(1.0, q, h)
  731. if q is None:
  732. q = diag(ones(n, dtype=typecode))
  733. return hq, q