File: SVD.cpp

package info (click to toggle)
freemat 4.2%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 142,116 kB
  • sloc: ansic: 126,788; cpp: 62,015; python: 2,080; perl: 1,255; sh: 1,146; yacc: 1,019; lex: 239; makefile: 107
file content (558 lines) | stat: -rw-r--r-- 22,150 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/*
 * Copyright (c) 2009 Samit Basu
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "Array.hpp"
#include "MemPtr.hpp"
#include "LAPACK.hpp"
#include "Algorithms.hpp"
#include <QtCore>


template <typename T>
static void Tgesvd(char* JOBU, char *JOBV, int* M, int *N, T* A, int *LDA, T *S, 
		   T *U, int *LDU, T *VT, int *LDVT, T *WORK,
		   int *LWORK, int *INFO, ftnlen l1, ftnlen l2);

template <>
void Tgesvd(char* JOBU, char* JOBV, int* M, int *N, float* A, int *LDA, float *S, 
		   float *U, int *LDU, float *VT, int *LDVT, float *WORK,
		   int *LWORK, int *INFO, ftnlen l1, ftnlen l2) {
  sgesvd_(JOBU,JOBV,M,N,A,LDA,S,U,LDU,VT,LDVT,WORK,LWORK,INFO,l1,l2);
}

template <>
void Tgesvd(char* JOBU, char* JOBV, int* M, int *N, double* A, int *LDA, double *S, 
		   double *U, int *LDU, double *VT, int *LDVT, double *WORK,
		   int *LWORK, int *INFO, ftnlen l1, ftnlen l2) {
  dgesvd_(JOBU,JOBV,M,N,A,LDA,S,U,LDU,VT,LDVT,WORK,LWORK,INFO,l1,l2);
}

template <typename T>
static void Tgesvd(char* JOBU, char *JOBV, int* M, int *N, T* A, int *LDA, T *S, 
		   T *U, int *LDU, T *VT, int *LDVT, T *WORK,
		   int *LWORK, T *RWORK, int *INFO, ftnlen l1, ftnlen l2);

template <>
void Tgesvd(char* JOBU, char *JOBV, int* M, int *N, float* A, int *LDA, float *S, 
		   float *U, int *LDU, float *VT, int *LDVT, float *WORK,
		   int *LWORK, float *RWORK, int *INFO, ftnlen l1, ftnlen l2) {
  cgesvd_(JOBU,JOBV,M,N,A,LDA,S,U,LDU,VT,LDVT,WORK,LWORK,RWORK,INFO,l1,l2);
}

template <>
void Tgesvd(char* JOBU, char *JOBV, int* M, int *N, double* A, int *LDA, double *S, 
		   double *U, int *LDU, double *VT, int *LDVT, double *WORK,
		   int *LWORK, double *RWORK, int *INFO, ftnlen l1, ftnlen l2) {
  zgesvd_(JOBU,JOBV,M,N,A,LDA,S,U,LDU,VT,LDVT,WORK,LWORK,RWORK,INFO,l1,l2);
}


template <typename T>
static void TSVD(int nrows, int ncols, BasicArray<T> &U, BasicArray<T> &VT, 
		 BasicArray<T> &S, BasicArray<T> &A, bool compact, bool vectors) {
  if (nrows*ncols == 0) return;
  // Here are the comments from the LAPACK routine SGESVD
  //      SUBROUTINE SGESVD( JOBU, JOBVT, M, N, A, LDA, S, U, LDU, VT, LDVT,
  //     $                   WORK, LWORK, INFO )
  //*
  //*  -- LAPACK driver routine (version 3.0) --
  //*     Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
  //*     Courant Institute, Argonne National Lab, and Rice University
  //*     October 31, 1999
  //*
  //*     .. Scalar Arguments ..
  //      CHARACTER          JOBU, JOBVT
  //      INTEGER            INFO, LDA, LDU, LDVT, LWORK, M, N
  //*     ..
  //*     .. Array Arguments ..
  //      REAL               A( LDA, * ), S( * ), U( LDU, * ),
  //     $                   VT( LDVT, * ), WORK( * )
  //*     ..
  //*
  //*  Purpose
  //*  =======
  //*
  //*  SGESVD computes the singular value decomposition (SVD) of a real
  //*  M-by-N matrix A, optionally computing the left and/or right singular
  //*  vectors. The SVD is written
  //*
  //*       A = U * SIGMA * transpose(V)
  //*
  //*  where SIGMA is an M-by-N matrix which is zero except for its
  //*  min(m,n) diagonal elements, U is an M-by-M orthogonal matrix, and
  //*  V is an N-by-N orthogonal matrix.  The diagonal elements of SIGMA
  //*  are the singular values of A; they are real and non-negative, and
  //*  are returned in descending order.  The first min(m,n) columns of
  //*  U and V are the left and right singular vectors of A.
  //*
  //*  Note that the routine returns V**T, not V.
  //*
  //*  Arguments
  //*  =========
  //*
  //*  JOBU    (input) CHARACTER*1
  //*          Specifies options for computing all or part of the matrix U:
  //*          = 'A':  all M columns of U are returned in array U:
  //*          = 'S':  the first min(m,n) columns of U (the left singular
  //*                  vectors) are returned in the array U;
  //*          = 'O':  the first min(m,n) columns of U (the left singular
  //*                  vectors) are overwritten on the array A;
  //*          = 'N':  no columns of U (no left singular vectors) are
  //*                  computed.
  //*
  char JOBU;
  if (!vectors)
    JOBU = 'N';
  else {
    if (!compact)
      JOBU = 'A';
    else
      JOBU = 'S';
  }
  //*  JOBVT   (input) CHARACTER*1
  //*          Specifies options for computing all or part of the matrix
  //*          V**T:
  //*          = 'A':  all N rows of V**T are returned in the array VT;
  //*          = 'S':  the first min(m,n) rows of V**T (the right singular
  //*                  vectors) are returned in the array VT;
  //*          = 'O':  the first min(m,n) rows of V**T (the right singular
  //*                  vectors) are overwritten on the array A;
  //*          = 'N':  no rows of V**T (no right singular vectors) are
  //*                  computed.
  //*
  //*          JOBVT and JOBU cannot both be 'O'.
  //*
  char JOBVT;
  if (!vectors)
    JOBVT = 'N';
  else
    JOBVT = 'A';
  //*  M       (input) INTEGER
  //*          The number of rows of the input matrix A.  M >= 0.
  //*
  int M = nrows;
  //*  N       (input) INTEGER
  //*          The number of columns of the input matrix A.  N >= 0.
  //*
  int N = ncols;
  //*  A       (input/output) REAL array, dimension (LDA,N)
  //*          On entry, the M-by-N matrix A.
  //*          On exit,
  //*          if JOBU = 'O',  A is overwritten with the first min(m,n)
  //*                          columns of U (the left singular vectors,
  //*                          stored columnwise);
  //*          if JOBVT = 'O', A is overwritten with the first min(m,n)
  //*                          rows of V**T (the right singular vectors,
  //*                          stored rowwise);
  //*          if JOBU .ne. 'O' and JOBVT .ne. 'O', the contents of A
  //*                          are destroyed.
  //*
  //*  LDA     (input) INTEGER
  //*          The leading dimension of the array A.  LDA >= max(1,M).
  //*
  int LDA = nrows;
  //*  S       (output) REAL array, dimension (min(M,N))
  //*          The singular values of A, sorted so that S(i) >= S(i+1).
  //*
  //*  U       (output) REAL array, dimension (LDU,UCOL)
  //*          (LDU,M) if JOBU = 'A' or (LDU,min(M,N)) if JOBU = 'S'.
  //*          If JOBU = 'A', U contains the M-by-M orthogonal matrix U;
  //*          if JOBU = 'S', U contains the first min(m,n) columns of U
  //*          (the left singular vectors, stored columnwise);
  //*          if JOBU = 'N' or 'O', U is not referenced.
  //*
  //*  LDU     (input) INTEGER
  //*          The leading dimension of the array U.  LDU >= 1; if
  //*          JOBU = 'S' or 'A', LDU >= M.
  //*
  int LDU = nrows;
  //*  VT      (output) REAL array, dimension (LDVT,N)
  //*          If JOBVT = 'A', VT contains the N-by-N orthogonal matrix
  //*          V**T;
  //*          if JOBVT = 'S', VT contains the first min(m,n) rows of
  //*          V**T (the right singular vectors, stored rowwise);
  //*          if JOBVT = 'N' or 'O', VT is not referenced.
  //*
  //*  LDVT    (input) INTEGER
  //*          The leading dimension of the array VT.  LDVT >= 1; if
  //*          JOBVT = 'A', LDVT >= N; if JOBVT = 'S', LDVT >= min(M,N).
  //*
  int LDVT = ncols;
  //*  WORK    (workspace/output) REAL array, dimension (LWORK)
  //*          On exit, if INFO = 0, WORK(1) returns the optimal LWORK;
  //*          if INFO > 0, WORK(2:MIN(M,N)) contains the unconverged
  //*          superdiagonal elements of an upper bidiagonal matrix B
  //*          whose diagonal is in S (not necessarily sorted). B
  //*          satisfies A = U * B * VT, so it has the same singular values
  //*          as A, and singular vectors related by U and VT.
  T WORKSIZE;
  //*  LWORK   (input) INTEGER
  //*          The dimension of the array WORK. LWORK >= 1.
  //*          LWORK >= MAX(3*MIN(M,N)+MAX(M,N),5*MIN(M,N)).
  //*          For good performance, LWORK should generally be larger.
  //*
  //*          If LWORK = -1, then a workspace query is assumed; the routine
  //*          only calculates the optimal size of the WORK array, returns
  //*          this value as the first entry of the WORK array, and no error
  //*          message related to LWORK is issued by XERBLA.
  //*
  int LWORK;
  //*  INFO    (output) INTEGER
  //*          = 0:  successful exit.
  //*          < 0:  if INFO = -i, the i-th argument had an illegal value.
  //*          > 0:  if SBDSQR did not converge, INFO specifies how many
  //*                superdiagonals of an intermediate bidiagonal form B
  //*                did not converge to zero. See the description of WORK
  //*                above for details.

  int INFO;
  LWORK = -1;
  Tgesvd(&JOBU,&JOBVT,&M,&N,A.data(),&LDA,S.data(),U.data(),&LDU,VT.data(),&LDVT,&WORKSIZE,&LWORK,&INFO,1,1);
  if (INFO < 0)
    WarningMessage(QString("svd (real) had illegal value for parameter (workspace) %1").arg(-INFO));
  LWORK = (int) WORKSIZE;
  MemBlock<T> WORK(LWORK);
  Tgesvd(&JOBU,&JOBVT,&M,&N,A.data(),&LDA,S.data(),U.data(),&LDU,VT.data(),&LDVT,&WORK,&LWORK,&INFO,1,1);
  if (INFO > 0)
    WarningMessage(QString("svd did not converge"));
  if (INFO < 0)
    WarningMessage(QString("svd (real) had illegal value for parameter %1").arg(-INFO));
}

template <typename T>
static void TSVD(int nrows, int ncols, BasicArray<T> &U, BasicArray<T> &VT, 
		 BasicArray<T> &S, BasicArray<T> &a_real, BasicArray<T> &a_imag, 
		 bool compact, bool vectors) {
  if (nrows*ncols == 0) return;
  // Here are the comments from the LAPACK routine CGESVD
  //
  //      SUBROUTINE CGESVD( JOBU, JOBVT, M, N, A, LDA, S, U, LDU, VT, LDVT,
  //     $                   WORK, LWORK, RWORK, INFO )
  //*
  //*  -- LAPACK driver routine (version 3.0) --
  //*     Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
  //*     Courant Institute, Argonne National Lab, and Rice University
  //*     October 31, 1999
  //*
  //*     .. Scalar Arguments ..
  //      CHARACTER          JOBU, JOBVT
  //      INTEGER            INFO, LDA, LDU, LDVT, LWORK, M, N
  //*     ..
  //*     .. Array Arguments ..
  //      REAL               RWORK( * ), S( * )
  //      COMPLEX            A( LDA, * ), U( LDU, * ), VT( LDVT, * ),
  //     $                   WORK( * )
  //*     ..
  //*
  //*  Purpose
  //*  =======
  //*
  //*  CGESVD computes the singular value decomposition (SVD) of a complex
  //*  M-by-N matrix A, optionally computing the left and/or right singular
  //*  vectors. The SVD is written
  //*
  //*       A = U * SIGMA * conjugate-transpose(V)
  //*
  //*  where SIGMA is an M-by-N matrix which is zero except for its
  //*  min(m,n) diagonal elements, U is an M-by-M unitary matrix, and
  //*  V is an N-by-N unitary matrix.  The diagonal elements of SIGMA
  //*  are the singular values of A; they are real and non-negative, and
  //*  are returned in descending order.  The first min(m,n) columns of
  //*  U and V are the left and right singular vectors of A.
  //*
  //*  Note that the routine returns V**H, not V.
  //*
  //*  Arguments
  //*  =========
  //*
  //*  JOBU    (input) CHARACTER*1
  //*          Specifies options for computing all or part of the matrix U:
  //*          = 'A':  all M columns of U are returned in array U:
  //*          = 'S':  the first min(m,n) columns of U (the left singular
  //*                  vectors) are returned in the array U;
  //*          = 'O':  the first min(m,n) columns of U (the left singular
  //*                  vectors) are overwritten on the array A;
  //*          = 'N':  no columns of U (no left singular vectors) are
  //*                  computed.
  //*
  char JOBU;
  if (!vectors)
    JOBU = 'N';
  else {
    if (!compact)
      JOBU = 'A';
    else
      JOBU = 'S';
  }
  //*  JOBVT   (input) CHARACTER*1
  //*          Specifies options for computing all or part of the matrix
  //*          V**H:
  //*          = 'A':  all N rows of V**H are returned in the array VT;
  //*          = 'S':  the first min(m,n) rows of V**H (the right singular
  //*                  vectors) are returned in the array VT;
  //*          = 'O':  the first min(m,n) rows of V**H (the right singular
  //*                  vectors) are overwritten on the array A;
  //*          = 'N':  no rows of V**H (no right singular vectors) are
  //*                  computed.
  //*
  //*          JOBVT and JOBU cannot both be 'O'.
  //*
  char JOBVT;
  if (!vectors)
    JOBVT = 'N';
  else
    JOBVT = 'A';
  //*  M       (input) INTEGER
  //*          The number of rows of the input matrix A.  M >= 0.
  //*
  int M = nrows;
  //*  N       (input) INTEGER
  //*          The number of columns of the input matrix A.  N >= 0.
  //*
  int N = ncols;
  //*  A       (input/output) COMPLEX array, dimension (LDA,N)
  //*          On entry, the M-by-N matrix A.
  //*          On exit,
  //*          if JOBU = 'O',  A is overwritten with the first min(m,n)
  //*                          columns of U (the left singular vectors,
  //*                          stored columnwise);
  //*          if JOBVT = 'O', A is overwritten with the first min(m,n)
  //*                          rows of V**H (the right singular vectors,
  //*                          stored rowwise);
  //*          if JOBU .ne. 'O' and JOBVT .ne. 'O', the contents of A
  //*                          are destroyed.
  //*
  BasicArray<T> A(MergeComplex(a_real,a_imag));
  //*  LDA     (input) INTEGER
  //*          The leading dimension of the array A.  LDA >= max(1,M).
  //*
  int LDA = nrows;    
  //*  S       (output) REAL array, dimension (min(M,N))
  //*          The singular values of A, sorted so that S(i) >= S(i+1).
  //*
  //*  U       (output) COMPLEX array, dimension (LDU,UCOL)
  //*          (LDU,M) if JOBU = 'A' or (LDU,min(M,N)) if JOBU = 'S'.
  //*          If JOBU = 'A', U contains the M-by-M unitary matrix U;
  //*          if JOBU = 'S', U contains the first min(m,n) columns of U
  //*          (the left singular vectors, stored columnwise);
  //*          if JOBU = 'N' or 'O', U is not referenced.
  //*
  //*  LDU     (input) INTEGER
  //*          The leading dimension of the array U.  LDU >= 1; if
  //*          JOBU = 'S' or 'A', LDU >= M.
  //*
  int LDU = nrows;    
  //*  VT      (output) COMPLEX array, dimension (LDVT,N)
  //*          If JOBVT = 'A', VT contains the N-by-N unitary matrix
  //*          V**H;
  //*          if JOBVT = 'S', VT contains the first min(m,n) rows of
  //*          V**H (the right singular vectors, stored rowwise);
  //*          if JOBVT = 'N' or 'O', VT is not referenced.
  //*
  //*  LDVT    (input) INTEGER
  //*          The leading dimension of the array VT.  LDVT >= 1; if
  //*          JOBVT = 'A', LDVT >= N; if JOBVT = 'S', LDVT >= min(M,N).
  //*
  int LDVT = ncols;
  //*  WORK    (workspace/output) COMPLEX array, dimension (LWORK)
  //*          On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
  //*
  T WORKSIZE[2];
  //*  LWORK   (input) INTEGER
  //*          The dimension of the array WORK. LWORK >= 1.
  //*          LWORK >=  2*MIN(M,N)+MAX(M,N).
  //*          For good performance, LWORK should generally be larger.
  //*
  //*          If LWORK = -1, then a workspace query is assumed; the routine
  //*          only calculates the optimal size of the WORK array, returns
  //*          this value as the first entry of the WORK array, and no error
  //*          message related to LWORK is issued by XERBLA.
  //*
  int LWORK;
  //*  RWORK   (workspace) REAL array, dimension (5*min(M,N))
  //*          On exit, if INFO > 0, RWORK(1:MIN(M,N)-1) contains the
  //*          unconverged superdiagonal elements of an upper bidiagonal
  //*          matrix B whose diagonal is in S (not necessarily sorted).
  //*          B satisfies A = U * B * VT, so it has the same singular
  //*          values as A, and singular vectors related by U and VT.
  //*
  int minMN;
  minMN = (M < N) ? M : N;
  MemBlock<T> RWORK(5*minMN);
  //*  INFO    (output) INTEGER
  //*          = 0:  successful exit.
  //*          < 0:  if INFO = -i, the i-th argument had an illegal value.
  //*          > 0:  if CBDSQR did not converge, INFO specifies how many
  //*                superdiagonals of an intermediate bidiagonal form B
  //*                did not converge to zero. See the description of RWORK
  //*                above for details.
  //*
  int INFO;
  LWORK = -1;
  Tgesvd( &JOBU, &JOBVT, &M, &N, A.data(), &LDA, S.data(), U.data(), &LDU, VT.data(), &LDVT, 
	  WORKSIZE, &LWORK, &RWORK, &INFO, 1, 1);
  LWORK = (int) WORKSIZE[0];
  MemBlock<T> WORK(LWORK*2);
  Tgesvd( &JOBU, &JOBVT, &M, &N, A.data(), &LDA, S.data(), U.data(), &LDU, VT.data(), &LDVT, 
	  &WORK, &LWORK, &RWORK, &INFO, 1, 1);
  if (INFO > 0)
    WarningMessage(QString("svd did not converge"));
  if (INFO < 0)
    WarningMessage(QString("svd had illegal value for parameter %1").arg(-INFO));
}


template <typename T>
static ArrayVector SVDFunction(BasicArray<T> &A, bool computevectors, bool compactform) {
  int nrows = int(A.rows());
  int ncols = int(A.cols());
  int mindim = (nrows < ncols) ? nrows : ncols;
  // A vector to store the singular values
  BasicArray<T> svals(NTuple(mindim,1));
  // A matrix to store the left singular vectors
  BasicArray<T> umat;
  // A matrix to store the right singular vectors
  BasicArray<T> vtmat;
  if (computevectors) 
    {
      if (!compactform) {
	umat = BasicArray<T>(NTuple(nrows,nrows));
	vtmat = BasicArray<T>(NTuple(ncols,ncols));
      } else {
	umat = BasicArray<T>(NTuple(nrows,mindim));
	vtmat = BasicArray<T>(NTuple(ncols,ncols));
      }
    }
  TSVD<T>(nrows,ncols,umat,vtmat,svals,A,compactform,computevectors);
  ArrayVector retval;
  if (!computevectors) {
    retval.push_back(Array(svals));
  } else {
    retval.push_back(Array(umat));
    BasicArray<T> smat;
    if (!compactform) 
      smat = BasicArray<T>(NTuple(A.rows(),A.cols()));
    else
      smat = BasicArray<T>(NTuple(mindim,A.cols()));
    for (index_t i=1;i<=mindim;i++)
      smat[NTuple(i,i)] = svals[i];
    retval.push_back(Array(smat));
    retval.push_back(Transpose(Array(vtmat)));
  }      
  return retval;
}

template <typename T>
static ArrayVector SVDFunction(BasicArray<T> &A_real, 
			       BasicArray<T> &A_imag,
			       bool computevectors, bool compactform) {
  int nrows = int(A_real.rows());
  int ncols = int(A_real.cols());
  int mindim = (nrows < ncols) ? nrows : ncols;
  // A vector to store the singular values
  BasicArray<T> svals(NTuple(mindim,1));
  // A matrix to store the left singular vectors
  BasicArray<T> umat;
  // A matrix to store the right singular vectors
  BasicArray<T> vtmat;
  if (computevectors) 
    {
      if (!compactform) {
	umat = BasicArray<T>(NTuple(2*nrows,nrows));
	vtmat = BasicArray<T>(NTuple(2*ncols,ncols));
      } else {
	umat = BasicArray<T>(NTuple(2*nrows,mindim));
	vtmat = BasicArray<T>(NTuple(2*ncols,ncols));
      }
    }
  TSVD<T>(nrows,ncols,umat,vtmat,svals,A_real,A_imag,compactform,computevectors);
  ArrayVector retval;
  if (!computevectors) {
    retval.push_back(Array(svals));
  } else {
    retval.push_back(Array(SplitReal(umat),SplitImag(umat)));
    BasicArray<T> smat_real;
    if (!compactform) {
      smat_real = BasicArray<T>(NTuple(A_real.rows(),A_real.cols()));
    } else {
      smat_real = BasicArray<T>(NTuple(mindim,A_real.cols()));
    }
    for (index_t i=1;i<=mindim;i++) {
      smat_real[NTuple(i,i)] = svals[i];
    }
    retval.push_back(Array(smat_real));
    retval.push_back(Hermitian(Array(SplitReal(vtmat),SplitImag(vtmat))));
  }
  return retval;
}

//@@Signature
//function svd SVDFunction jitsafe
//inputs A flag
//outputs U S V
//DOCBLOCK transforms_svd

ArrayVector SVDFunction(int nargout, const ArrayVector& arg) {
  if (arg.size() > 2)
    throw Exception("svd function takes at most two arguments");
  if (arg.size() < 1)
    throw Exception("svd function requries at least one argument - the matrix to decompose");
  Array A(arg[0].asDenseArray());
  bool compactform = false;
  if (arg.size() > 1) {
    Array flag(arg[1]);
    if (flag.asInteger() == 0)
      compactform = true;
  }
  // Test for numeric
  if (A.isReferenceType())
    throw Exception("Cannot apply svd to reference types.");
  if (!A.is2D())
    throw Exception("Cannot apply matrix operations to N-Dimensional arrays.");
  if (A.isSparse())
    throw Exception("SVD does not work with sparse matrices.");
  if (AnyNotFinite(A))
    throw Exception("SVD only defined for matrices with finite entries.");
  bool computevectors = (nargout>1);
  switch (A.dataClass()) {
  default: throw Exception("illegal argument type to svd");
  case Float:
    if (A.allReal())
      return SVDFunction(A.real<float>(),computevectors,compactform);
    else
      return SVDFunction(A.real<float>(),A.imag<float>(),computevectors,compactform);
    /*
    // Hack to address apparent bug in single precision SVD routines??
    Array Ad = A.toClass(Double);
    ArrayVector retvec;
    if (Ad.allReal())
    retvec = SVDFunction(Ad.real<double>(),computevectors,compactform);
    else
    retvec = SVDFunction(Ad.real<double>(),A.imag<double>(),computevectors,compactform);
    // Convert the results 
    for (int i=0;i<retvec.size();i++)
    retvec[i] = retvec[i].toClass(Float);
    return retvec;
    }*/
  case Double:
    if (A.allReal())
      return SVDFunction(A.real<double>(),computevectors,compactform);
    else
      return SVDFunction(A.real<double>(),A.imag<double>(),computevectors,compactform);
  }
}