Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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 Examples 

85 -------- 

86 >>> from scipy.linalg import cossin 

87 >>> from scipy.stats import unitary_group 

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

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

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

91 True 

92 

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

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

95 

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

97 ... compute_u=False) 

98 >>> print(ue) 

99 [] 

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

101 True 

102 

103 References 

104 ---------- 

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

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

107 

108 """ 

109 

110 if p or q: 

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

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

113 X = _asarray_validated(X, check_finite=True) 

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

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

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

117 m = X.shape[0] 

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

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

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

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

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

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

124 

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

126 elif not isinstance(X, Iterable): 

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

128 " containing the subblocks of X") 

129 else: 

130 if len(X) != 4: 

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

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

133 

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

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

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

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

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

139 p, q = x11.shape 

140 mmp, mmq = x22.shape 

141 

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

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

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

145 

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

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

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

149 

150 if p + mmp != q + mmq: 

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

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

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

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

155 

156 m = p + mmp 

157 

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

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

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

161 [x11, x12, x21, x22]) 

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

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

164 {'lwork': lwork}) 

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

166 compute_u1=compute_u, 

167 compute_u2=compute_u, 

168 compute_v1t=compute_vh, 

169 compute_v2t=compute_vh, 

170 trans=False, signs=swap_sign, 

171 **lwork_args) 

172 

173 method_name = csd.typecode + driver 

174 if info < 0: 

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

176 .format(-info, method_name)) 

177 if info > 0: 

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

179 

180 if separate: 

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

182 

183 U = block_diag(u1, u2) 

184 VDH = block_diag(v1h, v2h) 

185 

186 # Construct the middle factor CS 

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

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

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

190 n11 = min(p, q) - r 

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

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

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

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

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

196 

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

198 

199 xs = n11 + r 

200 xe = n11 + r + n12 

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

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

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

204 

205 xs = p + n22 + r 

206 xe = p + n22 + r + + n21 

207 ys = n11 + r 

208 ye = n11 + r + n21 

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

210 

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

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

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

214 

215 xs = n11 

216 xe = n11 + r 

217 ys = n11 + n21 + n22 + r 

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

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

220 

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

222 

223 return U, CS, VDH