Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/scipy/linalg/_decomp_cossin.py: 9%

81 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-12 06:31 +0000

1# -*- coding: utf-8 -*- 

2from collections.abc import Iterable 

3import numpy as np 

4 

5from scipy._lib._util import _asarray_validated 

6from scipy.linalg import block_diag, LinAlgError 

7from .lapack import _compute_lwork, get_lapack_funcs 

8 

9__all__ = ['cossin'] 

10 

11 

12def cossin(X, p=None, q=None, separate=False, 

13 swap_sign=False, compute_u=True, compute_vh=True): 

14 """ 

15 Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix. 

16 

17 X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following 

18 where upper left block has the shape of ``(p, q)``:: 

19 

20 ┌ ┐ 

21 │ I 0 0 │ 0 0 0 │ 

22 ┌ ┐ ┌ ┐│ 0 C 0 │ 0 -S 0 │┌ ┐* 

23 │ X11 │ X12 │ │ U1 │ ││ 0 0 0 │ 0 0 -I ││ V1 │ │ 

24 │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│ 

25 │ X21 │ X22 │ │ │ U2 ││ 0 0 0 │ I 0 0 ││ │ V2 │ 

26 └ ┘ └ ┘│ 0 S 0 │ 0 C 0 │└ ┘ 

27 │ 0 0 I │ 0 0 0 │ 

28 └ ┘ 

29 

30 ``U1``, ``U2``, ``V1``, ``V2`` are square orthogonal/unitary matrices of 

31 dimensions ``(p,p)``, ``(m-p,m-p)``, ``(q,q)``, and ``(m-q,m-q)`` 

32 respectively, and ``C`` and ``S`` are ``(r, r)`` nonnegative diagonal 

33 matrices satisfying ``C^2 + S^2 = I`` where ``r = min(p, m-p, q, m-q)``. 

34 

35 Moreover, the rank of the identity matrices are ``min(p, q) - r``, 

36 ``min(p, m - q) - r``, ``min(m - p, q) - r``, and ``min(m - p, m - q) - r`` 

37 respectively. 

38 

39 X can be supplied either by itself and block specifications p, q or its 

40 subblocks in an iterable from which the shapes would be derived. See the 

41 examples below. 

42 

43 Parameters 

44 ---------- 

45 X : array_like, iterable 

46 complex unitary or real orthogonal matrix to be decomposed, or iterable 

47 of subblocks ``X11``, ``X12``, ``X21``, ``X22``, when ``p``, ``q`` are 

48 omitted. 

49 p : int, optional 

50 Number of rows of the upper left block ``X11``, used only when X is 

51 given as an array. 

52 q : int, optional 

53 Number of columns of the upper left block ``X11``, used only when X is 

54 given as an array. 

55 separate : bool, optional 

56 if ``True``, the low level components are returned instead of the 

57 matrix factors, i.e. ``(u1,u2)``, ``theta``, ``(v1h,v2h)`` instead of 

58 ``u``, ``cs``, ``vh``. 

59 swap_sign : bool, optional 

60 if ``True``, the ``-S``, ``-I`` block will be the bottom left, 

61 otherwise (by default) they will be in the upper right block. 

62 compute_u : bool, optional 

63 if ``False``, ``u`` won't be computed and an empty array is returned. 

64 compute_vh : bool, optional 

65 if ``False``, ``vh`` won't be computed and an empty array is returned. 

66 

67 Returns 

68 ------- 

69 u : ndarray 

70 When ``compute_u=True``, contains the block diagonal orthogonal/unitary 

71 matrix consisting of the blocks ``U1`` (``p`` x ``p``) and ``U2`` 

72 (``m-p`` x ``m-p``) orthogonal/unitary matrices. If ``separate=True``, 

73 this contains the tuple of ``(U1, U2)``. 

74 cs : ndarray 

75 The cosine-sine factor with the structure described above. 

76 If ``separate=True``, this contains the ``theta`` array containing the 

77 angles in radians. 

78 vh : ndarray 

79 When ``compute_vh=True`, contains the block diagonal orthogonal/unitary 

80 matrix consisting of the blocks ``V1H`` (``q`` x ``q``) and ``V2H`` 

81 (``m-q`` x ``m-q``) orthogonal/unitary matrices. If ``separate=True``, 

82 this contains the tuple of ``(V1H, V2H)``. 

83 

84 References 

85 ---------- 

86 .. [1] Brian D. Sutton. Computing the complete CS decomposition. Numer. 

87 Algorithms, 50(1):33-65, 2009. 

88 

89 Examples 

90 -------- 

91 >>> import numpy as np 

92 >>> from scipy.linalg import cossin 

93 >>> from scipy.stats import unitary_group 

94 >>> x = unitary_group.rvs(4) 

95 >>> u, cs, vdh = cossin(x, p=2, q=2) 

96 >>> np.allclose(x, u @ cs @ vdh) 

97 True 

98 

99 Same can be entered via subblocks without the need of ``p`` and ``q``. Also 

100 let's skip the computation of ``u`` 

101 

102 >>> ue, cs, vdh = cossin((x[:2, :2], x[:2, 2:], x[2:, :2], x[2:, 2:]), 

103 ... compute_u=False) 

104 >>> print(ue) 

105 [] 

106 >>> np.allclose(x, u @ cs @ vdh) 

107 True 

108 

109 """ 

110 

111 if p or q: 

112 p = 1 if p is None else int(p) 

113 q = 1 if q is None else int(q) 

114 X = _asarray_validated(X, check_finite=True) 

115 if not np.equal(*X.shape): 

116 raise ValueError("Cosine Sine decomposition only supports square" 

117 " matrices, got {}".format(X.shape)) 

118 m = X.shape[0] 

119 if p >= m or p <= 0: 

120 raise ValueError("invalid p={}, 0<p<{} must hold" 

121 .format(p, X.shape[0])) 

122 if q >= m or q <= 0: 

123 raise ValueError("invalid q={}, 0<q<{} must hold" 

124 .format(q, X.shape[0])) 

125 

126 x11, x12, x21, x22 = X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:] 

127 elif not isinstance(X, Iterable): 

128 raise ValueError("When p and q are None, X must be an Iterable" 

129 " containing the subblocks of X") 

130 else: 

131 if len(X) != 4: 

132 raise ValueError("When p and q are None, exactly four arrays" 

133 " should be in X, got {}".format(len(X))) 

134 

135 x11, x12, x21, x22 = [np.atleast_2d(x) for x in X] 

136 for name, block in zip(["x11", "x12", "x21", "x22"], 

137 [x11, x12, x21, x22]): 

138 if block.shape[1] == 0: 

139 raise ValueError("{} can't be empty".format(name)) 

140 p, q = x11.shape 

141 mmp, mmq = x22.shape 

142 

143 if x12.shape != (p, mmq): 

144 raise ValueError("Invalid x12 dimensions: desired {}, " 

145 "got {}".format((p, mmq), x12.shape)) 

146 

147 if x21.shape != (mmp, q): 

148 raise ValueError("Invalid x21 dimensions: desired {}, " 

149 "got {}".format((mmp, q), x21.shape)) 

150 

151 if p + mmp != q + mmq: 

152 raise ValueError("The subblocks have compatible sizes but " 

153 "don't form a square array (instead they form a" 

154 " {}x{} array). This might be due to missing " 

155 "p, q arguments.".format(p + mmp, q + mmq)) 

156 

157 m = p + mmp 

158 

159 cplx = any([np.iscomplexobj(x) for x in [x11, x12, x21, x22]]) 

160 driver = "uncsd" if cplx else "orcsd" 

161 csd, csd_lwork = get_lapack_funcs([driver, driver + "_lwork"], 

162 [x11, x12, x21, x22]) 

163 lwork = _compute_lwork(csd_lwork, m=m, p=p, q=q) 

164 lwork_args = ({'lwork': lwork[0], 'lrwork': lwork[1]} if cplx else 

165 {'lwork': lwork}) 

166 *_, theta, u1, u2, v1h, v2h, info = csd(x11=x11, x12=x12, x21=x21, x22=x22, 

167 compute_u1=compute_u, 

168 compute_u2=compute_u, 

169 compute_v1t=compute_vh, 

170 compute_v2t=compute_vh, 

171 trans=False, signs=swap_sign, 

172 **lwork_args) 

173 

174 method_name = csd.typecode + driver 

175 if info < 0: 

176 raise ValueError('illegal value in argument {} of internal {}' 

177 .format(-info, method_name)) 

178 if info > 0: 

179 raise LinAlgError("{} did not converge: {}".format(method_name, info)) 

180 

181 if separate: 

182 return (u1, u2), theta, (v1h, v2h) 

183 

184 U = block_diag(u1, u2) 

185 VDH = block_diag(v1h, v2h) 

186 

187 # Construct the middle factor CS 

188 c = np.diag(np.cos(theta)) 

189 s = np.diag(np.sin(theta)) 

190 r = min(p, q, m - p, m - q) 

191 n11 = min(p, q) - r 

192 n12 = min(p, m - q) - r 

193 n21 = min(m - p, q) - r 

194 n22 = min(m - p, m - q) - r 

195 Id = np.eye(np.max([n11, n12, n21, n22, r]), dtype=theta.dtype) 

196 CS = np.zeros((m, m), dtype=theta.dtype) 

197 

198 CS[:n11, :n11] = Id[:n11, :n11] 

199 

200 xs = n11 + r 

201 xe = n11 + r + n12 

202 ys = n11 + n21 + n22 + 2 * r 

203 ye = n11 + n21 + n22 + 2 * r + n12 

204 CS[xs: xe, ys:ye] = Id[:n12, :n12] if swap_sign else -Id[:n12, :n12] 

205 

206 xs = p + n22 + r 

207 xe = p + n22 + r + + n21 

208 ys = n11 + r 

209 ye = n11 + r + n21 

210 CS[xs:xe, ys:ye] = -Id[:n21, :n21] if swap_sign else Id[:n21, :n21] 

211 

212 CS[p:p + n22, q:q + n22] = Id[:n22, :n22] 

213 CS[n11:n11 + r, n11:n11 + r] = c 

214 CS[p + n22:p + n22 + r, r + n21 + n22:2 * r + n21 + n22] = c 

215 

216 xs = n11 

217 xe = n11 + r 

218 ys = n11 + n21 + n22 + r 

219 ye = n11 + n21 + n22 + 2 * r 

220 CS[xs:xe, ys:ye] = s if swap_sign else -s 

221 

222 CS[p + n22:p + n22 + r, n11:n11 + r] = -s if swap_sign else s 

223 

224 return U, CS, VDH