Debian Codegraph @

src/dr/math/matrixAlgebra/RobustSingularValueDecomposition.java

raw symbols SCIP
1 /*
2 * RobustSingularValueDecomposition.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.math.matrixAlgebra;
27
28 import cern.colt.matrix.DoubleFactory2D;
29 import cern.colt.matrix.DoubleMatrix2D;
30 import cern.colt.matrix.linalg.Property;
31 import dr.math.MathUtils;
32
33
34 public class RobustSingularValueDecomposition implements java.io.Serializable {
35
36 static final long serialVersionUID = 1020;
37 /** Arrays for internal storage of U and V.
38 @serial internal storage of U.
39 @serial internal storage of V.
40 */
41 private double[][] U, V;
42
43 /** Array for internal storage of singular values.
44 @serial internal storage of singular values.
45 */
46 private double[] s;
47
48 /** Row and column dimensions.
49 @serial row dimension.
50 @serial column dimension.
51 */
52 private int m, n;
53
54 // private int maxIterations;
55
56 static private int maxIterationsDefault = 100000;
57
58 private static final String ERROR_STRING = "SVD is not converged.";
59
60 /**
61 Constructs and returns a new singular value decomposition object;
62 The decomposed matrices can be retrieved via instance methods of the returned decomposition object.
63 @param A A rectangular matrix.
64 @return A decomposition object to access <tt>U</tt>, <tt>S</tt> and <tt>V</tt>.
65 @throws IllegalArgumentException if <tt>A.rows() < A.columns()</tt>.
66 */
67 public RobustSingularValueDecomposition(DoubleMatrix2D Arg) throws ArithmeticException {
68 this(Arg,maxIterationsDefault);
69 }
70
71 public RobustSingularValueDecomposition(DoubleMatrix2D Arg, int maxIterations) throws ArithmeticException {
72 Property.DEFAULT.checkRectangular(Arg);
73
74 // this.maxIterations = maxIterations;
75
76 // Derived from LINPACK code.
77 // Initialize.
78 double[][] A = Arg.toArray();
79 m = Arg.rows();
80 n = Arg.columns();
81 int nu = Math.min(m,n);
82 s = new double [Math.min(m+1,n)];
83 U = new double [m][nu];
84 V = new double [n][n];
85 double[] e = new double [n];
86 double[] work = new double [m];
87 boolean wantu = true;
88 boolean wantv = true;
89
90 // Reduce A to bidiagonal form, storing the diagonal elements
91 // in s and the super-diagonal elements in e.
92
93 int nct = Math.min(m-1,n);
94 int nrt = Math.max(0,Math.min(n-2,m));
95 for (int k = 0; k < Math.max(nct,nrt); k++) {
96 if (k < nct) {
97
98 // Compute the transformation for the k-th column and
99 // place the k-th diagonal in s[k].
100 // Compute 2-norm of k-th column without under/overflow.
101 s[k] = 0;
102 for (int i = k; i < m; i++) {
103 s[k] = MathUtils.hypot(s[k],A[i][k]);
104 }
105 if (s[k] != 0.0) {
106 if (A[k][k] < 0.0) {
107 s[k] = -s[k];
108 }
109 for (int i = k; i < m; i++) {
110 A[i][k] /= s[k];
111 }
112 A[k][k] += 1.0;
113 }
114 s[k] = -s[k];
115 }
116 for (int j = k+1; j < n; j++) {
117 if ((k < nct) & (s[k] != 0.0)) {
118
119 // Apply the transformation.
120
121 double t = 0;
122 for (int i = k; i < m; i++) {
123 t += A[i][k]*A[i][j];
124 }
125 t = -t/A[k][k];
126 for (int i = k; i < m; i++) {
127 A[i][j] += t*A[i][k];
128 }
129 }
130
131 // Place the k-th row of A into e for the
132 // subsequent calculation of the row transformation.
133
134 e[j] = A[k][j];
135 }
136 if (wantu & (k < nct)) {
137
138 // Place the transformation in U for subsequent back
139 // multiplication.
140
141 for (int i = k; i < m; i++) {
142 U[i][k] = A[i][k];
143 }
144 }
145 if (k < nrt) {
146
147 // Compute the k-th row transformation and place the
148 // k-th super-diagonal in e[k].
149 // Compute 2-norm without under/overflow.
150 e[k] = 0;
151 for (int i = k+1; i < n; i++) {
152 e[k] = MathUtils.hypot(e[k],e[i]);
153 }
154 if (e[k] != 0.0) {
155 if (e[k+1] < 0.0) {
156 e[k] = -e[k];
157 }
158 for (int i = k+1; i < n; i++) {
159 e[i] /= e[k];
160 }
161 e[k+1] += 1.0;
162 }
163 e[k] = -e[k];
164 if ((k+1 < m) & (e[k] != 0.0)) {
165
166 // Apply the transformation.
167
168 for (int i = k+1; i < m; i++) {
169 work[i] = 0.0;
170 }
171 for (int j = k+1; j < n; j++) {
172 for (int i = k+1; i < m; i++) {
173 work[i] += e[j]*A[i][j];
174 }
175 }
176 for (int j = k+1; j < n; j++) {
177 double t = -e[j]/e[k+1];
178 for (int i = k+1; i < m; i++) {
179 A[i][j] += t*work[i];
180 }
181 }
182 }
183 if (wantv) {
184
185 // Place the transformation in V for subsequent
186 // back multiplication.
187
188 for (int i = k+1; i < n; i++) {
189 V[i][k] = e[i];
190 }
191 }
192 }
193 }
194
195 // Set up the final bidiagonal matrix or order p.
196
197 int p = Math.min(n,m+1);
198 if (nct < n) {
199 s[nct] = A[nct][nct];
200 }
201 if (m < p) {
202 s[p-1] = 0.0;
203 }
204 if (nrt+1 < p) {
205 e[nrt] = A[nrt][p-1];
206 }
207 e[p-1] = 0.0;
208
209 // If required, generate U.
210
211 if (wantu) {
212 for (int j = nct; j < nu; j++) {
213 for (int i = 0; i < m; i++) {
214 U[i][j] = 0.0;
215 }
216 U[j][j] = 1.0;
217 }
218 for (int k = nct-1; k >= 0; k--) {
219 if (s[k] != 0.0) {
220 for (int j = k+1; j < nu; j++) {
221 double t = 0;
222 for (int i = k; i < m; i++) {
223 t += U[i][k]*U[i][j];
224 }
225 t = -t/U[k][k];
226 for (int i = k; i < m; i++) {
227 U[i][j] += t*U[i][k];
228 }
229 }
230 for (int i = k; i < m; i++ ) {
231 U[i][k] = -U[i][k];
232 }
233 U[k][k] = 1.0 + U[k][k];
234 for (int i = 0; i < k-1; i++) {
235 U[i][k] = 0.0;
236 }
237 } else {
238 for (int i = 0; i < m; i++) {
239 U[i][k] = 0.0;
240 }
241 U[k][k] = 1.0;
242 }
243 }
244 }
245
246 // If required, generate V.
247
248 if (wantv) {
249 for (int k = n-1; k >= 0; k--) {
250 if ((k < nrt) & (e[k] != 0.0)) {
251 for (int j = k+1; j < nu; j++) {
252 double t = 0;
253 for (int i = k+1; i < n; i++) {
254 t += V[i][k]*V[i][j];
255 }
256 t = -t/V[k+1][k];
257 for (int i = k+1; i < n; i++) {
258 V[i][j] += t*V[i][k];
259 }
260 }
261 }
262 for (int i = 0; i < n; i++) {
263 V[i][k] = 0.0;
264 }
265 V[k][k] = 1.0;
266 }
267 }
268
269 // Main iteration loop for the singular values.
270
271 int pp = p-1;
272 int iter = 0;
273 double eps = Math.pow(2.0,-52.0);
274 while (p > 0) {
275 int k,kase;
276
277 // Here is where a test for too many iterations would go.
278 if (iter > maxIterations)
279 throw new ArithmeticException(ERROR_STRING);
280
281 // This section of the program inspects for
282 // negligible elements in the s and e arrays. On
283 // completion the variables kase and k are set as follows.
284
285 // kase = 1 if s(p) and e[k-1] are negligible and k<p
286 // kase = 2 if s(k) is negligible and k<p
287 // kase = 3 if e[k-1] is negligible, k<p, and
288 // s(k), ..., s(p) are not negligible (qr step).
289 // kase = 4 if e(p-1) is negligible (convergence).
290
291 for (k = p-2; k >= -1; k--) {
292 if (k == -1) {
293 break;
294 }
295 if (Math.abs(e[k]) <= eps*(Math.abs(s[k]) + Math.abs(s[k+1]))) {
296 e[k] = 0.0;
297 break;
298 }
299 }
300 if (k == p-2) {
301 kase = 4;
302 } else {
303 int ks;
304 for (ks = p-1; ks >= k; ks--) {
305 if (ks == k) {
306 break;
307 }
308 double t = (ks != p ? Math.abs(e[ks]) : 0.) +
309 (ks != k+1 ? Math.abs(e[ks-1]) : 0.);
310 if (Math.abs(s[ks]) <= eps*t) {
311 s[ks] = 0.0;
312 break;
313 }
314 }
315 if (ks == k) {
316 kase = 3;
317 } else if (ks == p-1) {
318 kase = 1;
319 } else {
320 kase = 2;
321 k = ks;
322 }
323 }
324 k++;
325
326 // Perform the task indicated by kase.
327
328 switch (kase) {
329
330 // Deflate negligible s(p).
331
332 case 1: {
333 double f = e[p-2];
334 e[p-2] = 0.0;
335 for (int j = p-2; j >= k; j--) {
336 double t = MathUtils.hypot(s[j],f);
337 double cs = s[j]/t;
338 double sn = f/t;
339 s[j] = t;
340 if (j != k) {
341 f = -sn*e[j-1];
342 e[j-1] = cs*e[j-1];
343 }
344 if (wantv) {
345 for (int i = 0; i < n; i++) {
346 t = cs*V[i][j] + sn*V[i][p-1];
347 V[i][p-1] = -sn*V[i][j] + cs*V[i][p-1];
348 V[i][j] = t;
349 }
350 }
351 }
352 }
353 break;
354
355 // Split at negligible s(k).
356
357 case 2: {
358 double f = e[k-1];
359 e[k-1] = 0.0;
360 for (int j = k; j < p; j++) {
361 double t = MathUtils.hypot(s[j],f);
362 double cs = s[j]/t;
363 double sn = f/t;
364 s[j] = t;
365 f = -sn*e[j];
366 e[j] = cs*e[j];
367 if (wantu) {
368 for (int i = 0; i < m; i++) {
369 t = cs*U[i][j] + sn*U[i][k-1];
370 U[i][k-1] = -sn*U[i][j] + cs*U[i][k-1];
371 U[i][j] = t;
372 }
373 }
374 }
375 }
376 break;
377
378 // Perform one qr step.
379
380 case 3: {
381
382 // Calculate the shift.
383
384 double scale = Math.max(Math.max(Math.max(Math.max(
385 Math.abs(s[p-1]),Math.abs(s[p-2])),Math.abs(e[p-2])),
386 Math.abs(s[k])),Math.abs(e[k]));
387 double sp = s[p-1]/scale;
388 double spm1 = s[p-2]/scale;
389 double epm1 = e[p-2]/scale;
390 double sk = s[k]/scale;
391 double ek = e[k]/scale;
392 double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0;
393 double c = (sp*epm1)*(sp*epm1);
394 double shift = 0.0;
395 if ((b != 0.0) | (c != 0.0)) {
396 shift = Math.sqrt(b*b + c);
397 if (b < 0.0) {
398 shift = -shift;
399 }
400 shift = c/(b + shift);
401 }
402 double f = (sk + sp)*(sk - sp) + shift;
403 double g = sk*ek;
404
405 // Chase zeros.
406
407 for (int j = k; j < p-1; j++) {
408 double t = MathUtils.hypot(f,g);
409 double cs = f/t;
410 double sn = g/t;
411 if (j != k) {
412 e[j-1] = t;
413 }
414 f = cs*s[j] + sn*e[j];
415 e[j] = cs*e[j] - sn*s[j];
416 g = sn*s[j+1];
417 s[j+1] = cs*s[j+1];
418 if (wantv) {
419 for (int i = 0; i < n; i++) {
420 t = cs*V[i][j] + sn*V[i][j+1];
421 V[i][j+1] = -sn*V[i][j] + cs*V[i][j+1];
422 V[i][j] = t;
423 }
424 }
425 t = MathUtils.hypot(f,g);
426 cs = f/t;
427 sn = g/t;
428 s[j] = t;
429 f = cs*e[j] + sn*s[j+1];
430 s[j+1] = -sn*e[j] + cs*s[j+1];
431 g = sn*e[j+1];
432 e[j+1] = cs*e[j+1];
433 if (wantu && (j < m-1)) {
434 for (int i = 0; i < m; i++) {
435 t = cs*U[i][j] + sn*U[i][j+1];
436 U[i][j+1] = -sn*U[i][j] + cs*U[i][j+1];
437 U[i][j] = t;
438 }
439 }
440 }
441 e[p-2] = f;
442 iter = iter + 1;
443 }
444 break;
445
446 // Convergence.
447
448 case 4: {
449
450 // Make the singular values positive.
451
452 if (s[k] <= 0.0) {
453 s[k] = (s[k] < 0.0 ? -s[k] : 0.0);
454 if (wantv) {
455 for (int i = 0; i <= pp; i++) {
456 V[i][k] = -V[i][k];
457 }
458 }
459 }
460
461 // Order the singular values.
462
463 while (k < pp) {
464 if (s[k] >= s[k+1]) {
465 break;
466 }
467 double t = s[k];
468 s[k] = s[k+1];
469 s[k+1] = t;
470 if (wantv && (k < n-1)) {
471 for (int i = 0; i < n; i++) {
472 t = V[i][k+1]; V[i][k+1] = V[i][k]; V[i][k] = t;
473 }
474 }
475 if (wantu && (k < m-1)) {
476 for (int i = 0; i < m; i++) {
477 t = U[i][k+1]; U[i][k+1] = U[i][k]; U[i][k] = t;
478 }
479 }
480 k++;
481 }
482 iter = 0;
483 p--;
484 }
485 break;
486 }
487 }
488 }
489 /**
490 Returns the two norm condition number, which is <tt>max(S) / min(S)</tt>.
491 */
492 public double cond() {
493 return s[0]/s[Math.min(m,n)-1];
494 }
495 /**
496 Returns the diagonal matrix of singular values.
497 @return S
498 */
499 public DoubleMatrix2D getS() {
500 double[][] S = new double[n][n];
501 for (int i = 0; i < n; i++) {
502 for (int j = 0; j < n; j++) {
503 S[i][j] = 0.0;
504 }
505 S[i][i] = this.s[i];
506 }
507 return DoubleFactory2D.dense.make(S);
508 }
509 /**
510 Returns the diagonal of <tt>S</tt>, which is a one-dimensional array of singular values
511 @return diagonal of <tt>S</tt>.
512 */
513 public double[] getSingularValues() {
514 return s;
515 }
516 /**
517 Returns the left singular vectors <tt>U</tt>.
518 @return <tt>U</tt>
519 */
520 public DoubleMatrix2D getU() {
521 //return new DoubleMatrix2D(U,m,Math.min(m+1,n));
522 return DoubleFactory2D.dense.make(U).viewPart(0,0,m,Math.min(m+1,n));
523 }
524 /**
525 Returns the right singular vectors <tt>V</tt>.
526 @return <tt>V</tt>
527 */
528 public DoubleMatrix2D getV() {
529 return DoubleFactory2D.dense.make(V);
530 }
531 /**
532 Returns the two norm, which is <tt>max(S)</tt>.
533 */
534 public double norm2() {
535 return s[0];
536 }
537 /**
538 Returns the effective numerical matrix rank, which is the number of nonnegligible singular values.
539 */
540 public int rank() {
541 double eps = Math.pow(2.0,-52.0);
542 double tol = Math.max(m,n)*s[0]*eps;
543 int r = 0;
544 for (int i = 0; i < s.length; i++) {
545 if (s[i] > tol) {
546 r++;
547 }
548 }
549 return r;
550 }
551 /**
552 Returns a String with (propertyName, propertyValue) pairs.
553 Useful for debugging or to quickly get the rough picture.
554 For example,
555 <pre>
556 rank : 3
557 trace : 0
558 </pre>
559 */
560 public String toString() {
561 StringBuffer buf = new StringBuffer();
562 String unknown = "Illegal operation or error: ";
563
564 buf.append("---------------------------------------------------------------------\n");
565 buf.append("SingularValueDecomposition(A) --> cond(A), rank(A), norm2(A), U, S, V\n");
566 buf.append("---------------------------------------------------------------------\n");
567
568 buf.append("cond = ");
569 try { buf.append(String.valueOf(this.cond()));}
570 catch (IllegalArgumentException exc) { buf.append(unknown+exc.getMessage()); }
571
572 buf.append("\nrank = ");
573 try { buf.append(String.valueOf(this.rank()));}
574 catch (IllegalArgumentException exc) { buf.append(unknown+exc.getMessage()); }
575
576 buf.append("\nnorm2 = ");
577 try { buf.append(String.valueOf(this.norm2()));}
578 catch (IllegalArgumentException exc) { buf.append(unknown+exc.getMessage()); }
579
580 buf.append("\n\nU = ");
581 try { buf.append(String.valueOf(this.getU()));}
582 catch (IllegalArgumentException exc) { buf.append(unknown+exc.getMessage()); }
583
584 buf.append("\n\nS = ");
585 try { buf.append(String.valueOf(this.getS()));}
586 catch (IllegalArgumentException exc) { buf.append(unknown+exc.getMessage()); }
587
588 buf.append("\n\nV = ");
589 try { buf.append(String.valueOf(this.getV()));}
590 catch (IllegalArgumentException exc) { buf.append(unknown+exc.getMessage()); }
591
592 return buf.toString();
593 }
594 }
595
596
597