QrDecomposition.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace VisualMath.Accord.Math.Decompositions
  7. {
  8. using System;
  9. using VisualMath.Accord.Math;
  10. /// <summary>
  11. /// QR decomposition for a rectangular matrix.
  12. /// </summary>
  13. /// <remarks>
  14. /// <para>
  15. /// For an m-by-n matrix <c>A</c> with <c>m >= n</c>, the QR decomposition
  16. /// is an m-by-n orthogonal matrix <c>Q</c> and an n-by-n upper triangular
  17. /// matrix <c>R</c> so that <c>A = Q * R</c>.</para>
  18. /// <para>
  19. /// The QR decomposition always exists, even if the matrix does not have
  20. /// full rank, so the constructor will never fail. The primary use of the
  21. /// QR decomposition is in the least squares solution of nonsquare systems
  22. /// of simultaneous linear equations.
  23. /// This will fail if <see cref="FullRank"/> returns <see langword="false"/>.</para>
  24. /// </remarks>
  25. ///
  26. public sealed class QrDecomposition
  27. {
  28. private double[,] qr;
  29. private double[] Rdiag;
  30. /// <summary>Constructs a QR decomposition.</summary>
  31. /// <param name="value">The matrix A to be decomposed.</param>
  32. public QrDecomposition(double[,] value)
  33. : this(value, false)
  34. {
  35. }
  36. /// <summary>Constructs a QR decomposition.</summary>
  37. /// <param name="value">The matrix A to be decomposed.</param>
  38. /// <param name="transpose">True if the decomposition should be performed on
  39. /// the transpose of A rather than A itself, false otherwise. Default is false.</param>
  40. public QrDecomposition(double[,] value, bool transpose)
  41. {
  42. if (value == null)
  43. {
  44. throw new ArgumentNullException("value", "Matrix cannot be null.");
  45. }
  46. if ((!transpose && value.GetLength(0) < value.GetLength(1)) ||
  47. (transpose && value.GetLength(1) < value.GetLength(0)))
  48. {
  49. throw new ArgumentException("Matrix has more columns than rows.", "value");
  50. }
  51. this.qr = transpose ? value.Transpose() : (double[,])value.Clone();
  52. int rows = qr.GetLength(0);
  53. int cols = qr.GetLength(1);
  54. this.Rdiag = new double[cols];
  55. for (int k = 0; k < cols; k++)
  56. {
  57. // Compute 2-norm of k-th column without under/overflow.
  58. double nrm = 0;
  59. for (int i = k; i < rows; i++)
  60. {
  61. nrm = Tools.Hypotenuse(nrm, qr[i, k]);
  62. }
  63. if (nrm != 0.0)
  64. {
  65. // Form k-th Householder vector.
  66. if (qr[k, k] < 0)
  67. {
  68. nrm = -nrm;
  69. }
  70. for (int i = k; i < rows; i++)
  71. {
  72. qr[i, k] /= nrm;
  73. }
  74. qr[k, k] += 1.0;
  75. // Apply transformation to remaining columns.
  76. for (int j = k + 1; j < cols; j++)
  77. {
  78. double s = 0.0;
  79. for (int i = k; i < rows; i++)
  80. {
  81. s += qr[i, k] * qr[i, j];
  82. }
  83. s = -s / qr[k, k];
  84. for (int i = k; i < rows; i++)
  85. {
  86. qr[i, j] += s * qr[i, k];
  87. }
  88. }
  89. }
  90. this.Rdiag[k] = -nrm;
  91. }
  92. }
  93. /// <summary>Least squares solution of <c>A * X = B</c></summary>
  94. /// <param name="value">Right-hand-side matrix with as many rows as <c>A</c> and any number of columns.</param>
  95. /// <returns>A matrix that minimized the two norm of <c>Q * R * X - B</c>.</returns>
  96. /// <exception cref="T:System.ArgumentException">Matrix row dimensions must be the same.</exception>
  97. /// <exception cref="T:System.InvalidOperationException">Matrix is rank deficient.</exception>
  98. public double[,] Solve(double[,] value)
  99. {
  100. if (value == null)
  101. throw new ArgumentNullException("value", "Matrix cannot be null.");
  102. if (value.GetLength(0) != qr.GetLength(0))
  103. throw new ArgumentException("Matrix row dimensions must agree.");
  104. if (!this.FullRank)
  105. throw new InvalidOperationException("Matrix is rank deficient.");
  106. // Copy right hand side
  107. int count = value.GetLength(1);
  108. double[,] X = (double[,])value.Clone();
  109. int m = qr.GetLength(0);
  110. int n = qr.GetLength(1);
  111. // Compute Y = transpose(Q)*B
  112. for (int k = 0; k < n; k++)
  113. {
  114. for (int j = 0; j < count; j++)
  115. {
  116. double s = 0.0;
  117. for (int i = k; i < m; i++)
  118. s += qr[i, k] * X[i, j];
  119. s = -s / qr[k, k];
  120. for (int i = k; i < m; i++)
  121. X[i, j] += s * qr[i, k];
  122. }
  123. }
  124. // Solve R*X = Y;
  125. for (int k = n - 1; k >= 0; k--)
  126. {
  127. for (int j = 0; j < count; j++)
  128. X[k, j] /= Rdiag[k];
  129. for (int i = 0; i < k; i++)
  130. for (int j = 0; j < count; j++)
  131. X[i, j] -= X[k, j] * qr[i, k];
  132. }
  133. double[,] r = new double[n, count];
  134. for (int i = 0; i < n; i++)
  135. for (int j = 0; j < count; j++)
  136. r[i, j] = X[i, j];
  137. return r;
  138. }
  139. /// <summary>Least squares solution of <c>X * A = B</c></summary>
  140. /// <param name="value">Right-hand-side matrix with as many columns as <c>A</c> and any number of rows.</param>
  141. /// <returns>A matrix that minimized the two norm of <c>X * Q * R - B</c>.</returns>
  142. /// <exception cref="T:System.ArgumentException">Matrix column dimensions must be the same.</exception>
  143. /// <exception cref="T:System.InvalidOperationException">Matrix is rank deficient.</exception>
  144. public double[,] SolveTranspose(double[,] value)
  145. {
  146. if (value == null)
  147. throw new ArgumentNullException("value", "Matrix cannot be null.");
  148. if (value.GetLength(1) != qr.GetLength(0))
  149. throw new ArgumentException("Matrix row dimensions must agree.");
  150. if (!this.FullRank)
  151. throw new InvalidOperationException("Matrix is rank deficient.");
  152. // Copy right hand side
  153. int count = value.GetLength(0);
  154. double[,] X = value.Transpose();
  155. int m = qr.GetLength(0);
  156. int n = qr.GetLength(1);
  157. // Compute Y = transpose(Q)*B
  158. for (int k = 0; k < n; k++)
  159. {
  160. for (int j = 0; j < count; j++)
  161. {
  162. double s = 0.0;
  163. for (int i = k; i < m; i++)
  164. s += qr[i, k] * X[i, j];
  165. s = -s / qr[k, k];
  166. for (int i = k; i < m; i++)
  167. X[i, j] += s * qr[i, k];
  168. }
  169. }
  170. // Solve R*X = Y;
  171. for (int k = n - 1; k >= 0; k--)
  172. {
  173. for (int j = 0; j < count; j++)
  174. X[k, j] /= Rdiag[k];
  175. for (int i = 0; i < k; i++)
  176. for (int j = 0; j < count; j++)
  177. X[i, j] -= X[k, j] * qr[i, k];
  178. }
  179. double[,] r = new double[count, n];
  180. for (int i = 0; i < n; i++)
  181. for (int j = 0; j < count; j++)
  182. r[j, i] = X[i, j];
  183. return r;
  184. }
  185. /// <summary>Least squares solution of <c>A * X = B</c></summary>
  186. /// <param name="value">Right-hand-side matrix with as many rows as <c>A</c> and any number of columns.</param>
  187. /// <returns>A matrix that minimized the two norm of <c>Q * R * X - B</c>.</returns>
  188. /// <exception cref="T:System.ArgumentException">Matrix row dimensions must be the same.</exception>
  189. /// <exception cref="T:System.InvalidOperationException">Matrix is rank deficient.</exception>
  190. public double[] Solve(double[] value)
  191. {
  192. if (value == null)
  193. throw new ArgumentNullException("value");
  194. if (value.GetLength(0) != qr.GetLength(0))
  195. throw new ArgumentException("Matrix row dimensions must agree.");
  196. if (!this.FullRank)
  197. throw new InvalidOperationException("Matrix is rank deficient.");
  198. // Copy right hand side
  199. double[] X = (double[])value.Clone();
  200. int m = qr.GetLength(0);
  201. int n = qr.GetLength(1);
  202. // Compute Y = transpose(Q)*B
  203. for (int k = 0; k < n; k++)
  204. {
  205. double s = 0.0;
  206. for (int i = k; i < m; i++)
  207. s += qr[i, k] * X[i];
  208. s = -s / qr[k, k];
  209. for (int i = k; i < m; i++)
  210. X[i] += s * qr[i, k];
  211. }
  212. // Solve R*X = Y;
  213. for (int k = n - 1; k >= 0; k--)
  214. {
  215. X[k] /= Rdiag[k];
  216. for (int i = 0; i < k; i++)
  217. X[i] -= X[k] * qr[i, k];
  218. }
  219. return X;
  220. }
  221. /// <summary>Shows if the matrix <c>A</c> is of full rank.</summary>
  222. /// <value>The value is <see langword="true"/> if <c>R</c>, and hence <c>A</c>, has full rank.</value>
  223. public bool FullRank
  224. {
  225. get
  226. {
  227. int columns = qr.GetLength(1);
  228. for (int i = 0; i < columns; i++)
  229. {
  230. if (this.Rdiag[i] == 0)
  231. {
  232. return false;
  233. }
  234. }
  235. return true;
  236. }
  237. }
  238. /// <summary>Returns the upper triangular factor <c>R</c>.</summary>
  239. public double[,] UpperTriangularFactor
  240. {
  241. get
  242. {
  243. int n = this.qr.GetLength(1);
  244. double[,] x = new double[n, n];
  245. for (int i = 0; i < n; i++)
  246. {
  247. for (int j = 0; j < n; j++)
  248. {
  249. if (i < j)
  250. {
  251. x[i, j] = qr[i, j];
  252. }
  253. else if (i == j)
  254. {
  255. x[i, j] = Rdiag[i];
  256. }
  257. else
  258. {
  259. x[i, j] = 0.0;
  260. }
  261. }
  262. }
  263. return x;
  264. }
  265. }
  266. /// <summary>Returns the orthogonal factor <c>Q</c>.</summary>
  267. public double[,] OrthogonalFactor
  268. {
  269. get
  270. {
  271. int rows = qr.GetLength(0);
  272. int cols = qr.GetLength(1);
  273. double[,] x = new double[rows, cols];
  274. for (int k = cols - 1; k >= 0; k--)
  275. {
  276. for (int i = 0; i < rows; i++)
  277. {
  278. x[i, k] = 0.0;
  279. }
  280. x[k, k] = 1.0;
  281. for (int j = k; j < cols; j++)
  282. {
  283. if (qr[k, k] != 0)
  284. {
  285. double s = 0.0;
  286. for (int i = k; i < rows; i++)
  287. {
  288. s += qr[i, k] * x[i, j];
  289. }
  290. s = -s / qr[k, k];
  291. for (int i = k; i < rows; i++)
  292. {
  293. x[i, j] += s * qr[i, k];
  294. }
  295. }
  296. }
  297. }
  298. return x;
  299. }
  300. }
  301. /// <summary>Returns the diagonal of <c>R</c>.</summary>
  302. public double[] Diagonal
  303. {
  304. get { return Rdiag; }
  305. }
  306. /// <summary>Least squares solution of <c>A * X = I</c></summary>
  307. public double[,] Inverse()
  308. {
  309. if (!this.FullRank)
  310. throw new InvalidOperationException("Matrix is rank deficient.");
  311. // Copy right hand side
  312. int m = qr.GetLength(0);
  313. int n = qr.GetLength(1);
  314. double[,] X = new double[m, m];
  315. // Compute Y = transpose(Q)
  316. for (int k = n - 1; k >= 0; k--)
  317. {
  318. for (int i = 0; i < m; i++)
  319. X[k, i] = 0.0;
  320. X[k, k] = 1.0;
  321. for (int j = k; j < n; j++)
  322. {
  323. if (qr[k, k] != 0)
  324. {
  325. double s = 0.0;
  326. for (int i = k; i < m; i++)
  327. s += qr[i, k] * X[j, i];
  328. s = -s / qr[k, k];
  329. for (int i = k; i < m; i++)
  330. X[j, i] += s * qr[i, k];
  331. }
  332. }
  333. }
  334. // Solve R*X = Y;
  335. for (int k = n - 1; k >= 0; k--)
  336. {
  337. for (int j = 0; j < m; j++)
  338. X[k, j] /= Rdiag[k];
  339. for (int i = 0; i < k; i++)
  340. for (int j = 0; j < m; j++)
  341. X[i, j] -= X[k, j] * qr[i, k];
  342. }
  343. return X;
  344. }
  345. }
  346. }