_matfuncs_sqrtm.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. """
  2. Matrix square root for general matrices and for upper triangular matrices.
  3. This module exists to avoid cyclic imports.
  4. """
  5. from __future__ import division, print_function, absolute_import
  6. __all__ = ['sqrtm']
  7. import numpy as np
  8. from scipy._lib._util import _asarray_validated
  9. # Local imports
  10. from .misc import norm
  11. from .lapack import ztrsyl, dtrsyl
  12. from .decomp_schur import schur, rsf2csf
  13. class SqrtmError(np.linalg.LinAlgError):
  14. pass
  15. def _sqrtm_triu(T, blocksize=64):
  16. """
  17. Matrix square root of an upper triangular matrix.
  18. This is a helper function for `sqrtm` and `logm`.
  19. Parameters
  20. ----------
  21. T : (N, N) array_like upper triangular
  22. Matrix whose square root to evaluate
  23. blocksize : int, optional
  24. If the blocksize is not degenerate with respect to the
  25. size of the input array, then use a blocked algorithm. (Default: 64)
  26. Returns
  27. -------
  28. sqrtm : (N, N) ndarray
  29. Value of the sqrt function at `T`
  30. References
  31. ----------
  32. .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
  33. "Blocked Schur Algorithms for Computing the Matrix Square Root,
  34. Lecture Notes in Computer Science, 7782. pp. 171-182.
  35. """
  36. T_diag = np.diag(T)
  37. keep_it_real = np.isrealobj(T) and np.min(T_diag) >= 0
  38. if not keep_it_real:
  39. T_diag = T_diag.astype(complex)
  40. R = np.diag(np.sqrt(T_diag))
  41. # Compute the number of blocks to use; use at least one block.
  42. n, n = T.shape
  43. nblocks = max(n // blocksize, 1)
  44. # Compute the smaller of the two sizes of blocks that
  45. # we will actually use, and compute the number of large blocks.
  46. bsmall, nlarge = divmod(n, nblocks)
  47. blarge = bsmall + 1
  48. nsmall = nblocks - nlarge
  49. if nsmall * bsmall + nlarge * blarge != n:
  50. raise Exception('internal inconsistency')
  51. # Define the index range covered by each block.
  52. start_stop_pairs = []
  53. start = 0
  54. for count, size in ((nsmall, bsmall), (nlarge, blarge)):
  55. for i in range(count):
  56. start_stop_pairs.append((start, start + size))
  57. start += size
  58. # Within-block interactions.
  59. for start, stop in start_stop_pairs:
  60. for j in range(start, stop):
  61. for i in range(j-1, start-1, -1):
  62. s = 0
  63. if j - i > 1:
  64. s = R[i, i+1:j].dot(R[i+1:j, j])
  65. denom = R[i, i] + R[j, j]
  66. num = T[i, j] - s
  67. if denom != 0:
  68. R[i, j] = (T[i, j] - s) / denom
  69. elif denom == 0 and num == 0:
  70. R[i, j] = 0
  71. else:
  72. raise SqrtmError('failed to find the matrix square root')
  73. # Between-block interactions.
  74. for j in range(nblocks):
  75. jstart, jstop = start_stop_pairs[j]
  76. for i in range(j-1, -1, -1):
  77. istart, istop = start_stop_pairs[i]
  78. S = T[istart:istop, jstart:jstop]
  79. if j - i > 1:
  80. S = S - R[istart:istop, istop:jstart].dot(R[istop:jstart,
  81. jstart:jstop])
  82. # Invoke LAPACK.
  83. # For more details, see the solve_sylvester implemention
  84. # and the fortran dtrsyl and ztrsyl docs.
  85. Rii = R[istart:istop, istart:istop]
  86. Rjj = R[jstart:jstop, jstart:jstop]
  87. if keep_it_real:
  88. x, scale, info = dtrsyl(Rii, Rjj, S)
  89. else:
  90. x, scale, info = ztrsyl(Rii, Rjj, S)
  91. R[istart:istop, jstart:jstop] = x * scale
  92. # Return the matrix square root.
  93. return R
  94. def sqrtm(A, disp=True, blocksize=64):
  95. """
  96. Matrix square root.
  97. Parameters
  98. ----------
  99. A : (N, N) array_like
  100. Matrix whose square root to evaluate
  101. disp : bool, optional
  102. Print warning if error in the result is estimated large
  103. instead of returning estimated error. (Default: True)
  104. blocksize : integer, optional
  105. If the blocksize is not degenerate with respect to the
  106. size of the input array, then use a blocked algorithm. (Default: 64)
  107. Returns
  108. -------
  109. sqrtm : (N, N) ndarray
  110. Value of the sqrt function at `A`
  111. errest : float
  112. (if disp == False)
  113. Frobenius norm of the estimated error, ||err||_F / ||A||_F
  114. References
  115. ----------
  116. .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
  117. "Blocked Schur Algorithms for Computing the Matrix Square Root,
  118. Lecture Notes in Computer Science, 7782. pp. 171-182.
  119. Examples
  120. --------
  121. >>> from scipy.linalg import sqrtm
  122. >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
  123. >>> r = sqrtm(a)
  124. >>> r
  125. array([[ 0.75592895, 1.13389342],
  126. [ 0.37796447, 1.88982237]])
  127. >>> r.dot(r)
  128. array([[ 1., 3.],
  129. [ 1., 4.]])
  130. """
  131. A = _asarray_validated(A, check_finite=True, as_inexact=True)
  132. if len(A.shape) != 2:
  133. raise ValueError("Non-matrix input to matrix function.")
  134. if blocksize < 1:
  135. raise ValueError("The blocksize should be at least 1.")
  136. keep_it_real = np.isrealobj(A)
  137. if keep_it_real:
  138. T, Z = schur(A)
  139. if not np.array_equal(T, np.triu(T)):
  140. T, Z = rsf2csf(T, Z)
  141. else:
  142. T, Z = schur(A, output='complex')
  143. failflag = False
  144. try:
  145. R = _sqrtm_triu(T, blocksize=blocksize)
  146. ZH = np.conjugate(Z).T
  147. X = Z.dot(R).dot(ZH)
  148. except SqrtmError:
  149. failflag = True
  150. X = np.empty_like(A)
  151. X.fill(np.nan)
  152. if disp:
  153. if failflag:
  154. print("Failed to find a square root.")
  155. return X
  156. else:
  157. try:
  158. arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro')
  159. except ValueError:
  160. # NaNs in matrix
  161. arg2 = np.inf
  162. return X, arg2