-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy patheigs_new.m
1563 lines (1477 loc) · 58.9 KB
/
eigs_new.m
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function varargout = eigs(varargin)
%EIGS Find a few eigenvalues and eigenvectors of a matrix using ARPACK
% D = EIGS(A) returns a vector of A's 6 largest magnitude eigenvalues.
% A must be square and should be large and sparse.
%
% [V,D] = EIGS(A) returns a diagonal matrix D of A's 6 largest magnitude
% eigenvalues and a matrix V whose columns are the corresponding
% eigenvectors.
%
% [V,D,FLAG] = EIGS(A) also returns a convergence flag. If FLAG is 0 then
% all the eigenvalues converged; otherwise not all converged.
%
% EIGS(A,B) solves the generalized eigenvalue problem A*V == B*V*D. B
% must be symmetric (or Hermitian) positive definite and the same size as
% A. EIGS(A,[],...) indicates the standard eigenvalue problem A*V == V*D.
%
% EIGS(A,K) and EIGS(A,B,K) return the K largest magnitude eigenvalues.
%
% EIGS(A,K,SIGMA) and EIGS(A,B,K,SIGMA) return K eigenvalues. If SIGMA is:
% 'LM' or 'SM' - Largest or Smallest Magnitude
% For real symmetric problems, SIGMA may also be:
% 'LA' or 'SA' - Largest or Smallest Algebraic
% 'BE' - Both Ends, one more from high end if K is odd
% For nonsymmetric and complex problems, SIGMA may also be:
% 'LR' or 'SR' - Largest or Smallest Real part
% 'LI' or 'SI' - Largest or Smallest Imaginary part
% If SIGMA is a real or complex scalar including 0, EIGS finds the
% eigenvalues closest to SIGMA. For scalar SIGMA, and when SIGMA = 'SM',
% B need only be symmetric (or Hermitian) positive semi-definite since it
% is not Cholesky factored as in the other cases.
%
% EIGS(A,K,SIGMA,OPTS) and EIGS(A,B,K,SIGMA,OPTS) specify options:
% OPTS.issym: symmetry of A or A-SIGMA*B represented by AFUN [{false} |
% true]
% OPTS.isreal: complexity of A or A-SIGMA*B represented by AFUN [false | {true}]
% OPTS.tol: convergence: Ritz estimate residual <= tol*NORM(A) [scalar | {eps}]
% OPTS.maxit: maximum number of iterations [integer | {300}]
% OPTS.p: number of Lanczos vectors: K+1<p<=N [integer | {2K}]
% OPTS.v0: starting vector [N-by-1 vector | {randomly generated}]
% OPTS.disp: diagnostic information display level [0 | {1} | 2]
% OPTS.cholB: B is actually its Cholesky factor CHOL(B) [{false} | true]
% OPTS.permB: sparse B is actually CHOL(B(permB,permB)) [permB | {1:N}]
% Use CHOL(B) instead of B when SIGMA is a string other than 'SM'.
%
% EIGS(AFUN,N) accepts the function AFUN instead of the matrix A. AFUN is
% a function handle and Y = AFUN(X) should return
% A*X if SIGMA is unspecified, or a string other than 'SM'
% A\X if SIGMA is 0 or 'SM'
% (A-SIGMA*I)\X if SIGMA is a nonzero scalar (standard problem)
% (A-SIGMA*B)\X if SIGMA is a nonzero scalar (generalized problem)
% N is the size of A. The matrix A, A-SIGMA*I or A-SIGMA*B represented by
% AFUN is assumed to be real and nonsymmetric unless specified otherwise
% by OPTS.isreal and OPTS.issym. In all these EIGS syntaxes, EIGS(A,...)
% may be replaced by EIGS(AFUN,N,...).
%
% Example:
% A = delsq(numgrid('C',15)); d1 = eigs(A,5,'SM');
%
% Equivalently, if dnRk is the following one-line function:
% %----------------------------%
% function y = dnRk(x,R,k)
% y = (delsq(numgrid(R,k))) \ x;
% %----------------------------%
%
% n = size(A,1); opts.issym = 1;
% d2 = eigs(@(x)dnRk(x,'C',15),n,5,'SM',opts);
%
% See also EIG, SVDS, ARPACKC, FUNCTION_HANDLE.
% Copyright 1984-2008 The MathWorks, Inc.
% $Revision: 1.45.4.11 $ $Date: 2008/12/01 07:19:19 $
% EIGS provides the reverse communication interface to ARPACK library
% routines. EIGS attempts to provide an interface for as many different
% algorithms as possible. The reverse communication interfaces are
% documented in the ARPACK Users' Guide, ISBN 0-89871-407-9.
cputms = zeros(5,1);
t0 = cputime; % start timing pre-processing
% Process inputs and do error-checking
if (nargout > 3)
error('MATLAB:eigs:TooManyOutputs', 'Too many output arguments.')
end
% Platform dependent integer type
if strfind(computer, '64')
intconvert = @(arraytoconvert) int64(arraytoconvert);
inttype = 'int64';
else
intconvert = @(arraytoconvert) int32(arraytoconvert);
inttype = 'int32';
end
% Error check inputs and derive some information from them
[A,Amatrix,isrealprob,issymA,n,B,classAB,k,eigs_sigma,whch, ...
sigma,tol,maxit,p,info,eigs_display,cholB,permB,resid,useeig, ...
afunNargs,style,mode,Afactors,Bfactors] = ...
checkInputs(varargin{:});
% Now have enough information to do early return on cases EIGS does not
% handle. For these cases, use the full EIG code.
if useeig
fullEig(nargout);
return
end
if ~isempty(Afactors)
L = Afactors.L; Afactors.L = [];
U = Afactors.U; Afactors.U = [];
pp = Afactors.pp; Afactors.pp = [];
qq = Afactors.qq; Afactors.qq = [];
dgAsB = Afactors.dgAsB; Afactors.dgAsB = [];
clear Afactors;
end
if ~isempty(Bfactors)
BisHpd = Bfactors.BisHpd;
if BisHpd
RB = Bfactors.RB; Bfactors.RB = [];
RBT = Bfactors.RBT; Bfactors.RBT = [];
permB = Bfactors.permB; Bfactors.permB = [];
else
LB = Bfactors.LB; Bfactors.LB = [];
UB = Bfactors.UB; Bfactors.UB = [];
ppB = Bfactors.ppB; Bfactors.ppB = [];
qqB = Bfactors.qqB; Bfactors.qqB = [];
dgB = Bfactors.dgB; Bfactors.dgB = [];
end
clear Bfactors;
end
if isempty(B)
if mode ~= 3
% OP = A
applyOP = @(v)Amtimes(v);
else
% OP = (A-\sigma*I)^{-1}
applyOP = @(v)AminusSigmaBsolve(v);
end
else
if mode ~= 3 && BisHpd == true
% OP = L^{-1}AL^{-T} (B = LL^T)
applyOP = @(v)RBTsolve(Amtimes(RBsolve(v)));
elseif mode ~= 3 && BisHpd == false
% OP = U^{-1}L^{-1}A (B = LU)
applyOP = @(v)Bsolve(Amtimes(v));
else
% OP = (A-\sigma*B)^{-1}B
applyOP = @(v)AminusSigmaBsolve(Bmtimes(v));
end
end
if strcmp(style,'G')
if ~isempty(B) && BisHpd == true && mode == 3
applyM = @(v) Bmtimes(v);
else
applyM = @(v) v;
end
end
% Allocate outputs and ARPACK work variables
if isrealprob
if issymA % real and symmetric
if strcmp(classAB,'single')
aupdfun = 'ssaupd';
eupdfun = 'sseupd';
else
aupdfun = 'dsaupd';
eupdfun = 'dseupd';
end
lworkl = intconvert(p*(p+8));
d = zeros(k,1,classAB);
else % real but not symmetric
if strcmp(classAB,'single')
aupdfun = 'snaupd';
eupdfun = 'sneupd';
else
aupdfun = 'dnaupd';
eupdfun = 'dneupd';
end
lworkl = intconvert(3*p*(p+2));
workev = zeros(3*p,1,classAB);
d = zeros(k+1,1,classAB);
di = zeros(k+1,1,classAB);
end
v = zeros(n,p,classAB);
workd = zeros(n,3,classAB);
workl = zeros(lworkl,1,classAB);
else % complex
if strcmp(classAB,'single')
aupdfun = 'cnaupd';
eupdfun = 'cneupd';
else
aupdfun = 'znaupd';
eupdfun = 'zneupd';
end
zv = zeros(2*n*p,1,classAB);
workd = complex(zeros(n,3,classAB));
zworkd = zeros(2*numel(workd),1,classAB);
lworkl = intconvert(2*(3*p^2+5*p));
workl = zeros(lworkl,1,classAB);
workev = zeros(2*2*p,1,classAB);
zd = zeros(2*(k+1),1,classAB);
rwork = zeros(p,1,classAB);
end
ldv = intconvert(n);
ipntr = zeros(15,1,inttype);
ido = intconvert(0); % reverse communication parameter, initial value
if strcmp(style,'S')
bmat = 'I'; % standard eigenvalue problem
else
bmat = 'G'; % generalized eigenvalue problem
end
nev = intconvert(k); % number of eigenvalues requested
ncv = intconvert(p); % number of Lanczos vectors
iparam = zeros(11,1,inttype);
% iparam(1) = ishift = 1 ensures we are never asked to handle ido=3
iparam([1 3 7]) = [1 maxit mode];
select = zeros(p,1,inttype);
% To Do: Remove this error when ARPACKC supports singles
if strcmp(classAB,'single')
error('MATLAB:eigs:single', ...
'EIGS does not support single precision inputs.')
end
% The ARPACK routines return to EIGS many times per each iteration but we
% only want to display the Ritz values once per iteration (if opts.disp>0).
% Keep track of whether we've displayed this iteration yet in eigs_iter.
eigs_iter = 0;
cputms(1) = cputime - t0; % end timing pre-processing
% Iterate until ARPACK's reverse communication parameter ido says to stop
while (ido ~= 99)
t0 = cputime; % start timing ARPACK calls **aupd
if isrealprob
arpackc( aupdfun, ido, ...
bmat, intconvert(n), whch, nev, tol, resid, ncv, ...
v, ldv, iparam, ipntr, workd, workl, lworkl, info );
else
% The FORTRAN ARPACK routine expects the complex input zworkd to have
% real and imaginary parts interleaved, but the OP about to be
% applied to workd expects it in MATLAB's complex representation with
% separate real and imaginary parts. Thus we need both.
zworkd(1:2:end-1) = real(workd);
zworkd(2:2:end) = imag(workd);
arpackc( aupdfun, ido, ...
bmat, intconvert(n), whch, nev, tol, resid, ncv, ...
zv, ldv, iparam, ipntr, zworkd, workl, lworkl, rwork, info );
workd = reshape(complex(zworkd(1:2:end-1),zworkd(2:2:end)),[n,3]);
end
if (info < 0)
error('MATLAB:eigs:ARPACKroutineError', ...
'Error with ARPACK routine %s: info = %d', ...
aupdfun,full(double(info)))
end
cputms(2) = cputms(2) + (cputime-t0); % end timing ARPACK calls **aupd
t0 = cputime; % start timing MATLAB OP(X)
% Compute which columns of workd ipntr references
cols = checkIpntr;
% The ARPACK reverse communication parameter ido tells EIGS what to do
switch ido
case -1
workd(:,cols(2)) = applyOP(workd(:,cols(1)));
if strcmp(style,'G') && mode ~= 3
workd(:,cols(1)) = workd(:,cols(2));
end
case 1
if strcmp(style,'G') && mode == 3 && (isempty(B) || BisHpd)
% use with B-inner product for mode 3; see applyM
workd(:,cols(2)) = AminusSigmaBsolve(workd(:,cols(3)));
else
% same work as case -1
workd(:,cols(2)) = applyOP(workd(:,cols(1)));
if strcmp(style,'G') && mode ~= 3
% use with std inner product; see applyM
workd(:,cols(1)) = workd(:,cols(2));
end
end
case 2
workd(:,cols(2)) = applyM(workd(:,cols(1)));
case 99
% ARPACK has converged
otherwise
error('MATLAB:eigs:UnknownIdo','Unknown ido.');
end
cputms(3) = cputms(3) + (cputime-t0); % end timing MATLAB OP(X)
if eigs_display
displayRitzValues;
end
end % while (ido ~= 99)
t0 = cputime; % start timing post-processing
if (info < 0)
error('MATLAB:eigs:ARPACKroutineError', ...
'Error with ARPACK routine %s: info = %d',aupdfun,full(info));
end % if (info < 0)
if (nargout >= 2)
rvec = intconvert(true); % compute eigenvectors
else
rvec = intconvert(false); % do not compute eigenvectors
end
if isrealprob
if issymA
arpackc( eupdfun, rvec, 'A', select, ...
d, v, ldv, sigma, ...
bmat, intconvert(n), whch, nev, tol, resid, ncv, ...
v, ldv, iparam, ipntr, workd, workl, lworkl, info );
if strcmp(whch,'LM') || strcmp(whch,'LA')
d = flipud(d);
if (rvec == 1)
v(:,1:k) = v(:,k:-1:1);
end
end
if ((strcmp(whch,'SM') || strcmp(whch,'SA')) && (rvec == 0))
d = flipud(d);
end
else
% If sigma is complex, isrealprob=true and we use [c,z]neupd.
% So use sigmar=sigma and sigmai=0 here in dneupd.
arpackc( eupdfun, rvec, 'A', select, ...
d, di, v, ldv, sigma, 0, workev, ...
bmat, intconvert(n), whch, nev, tol, resid, ncv, ...
v, ldv, iparam, ipntr, workd, workl, lworkl, info );
d = complex(d,di);
if rvec
d(k+1) = [];
else
zind = find(d == 0);
if isempty(zind)
d = d(k+1:-1:2);
else
d(max(zind)) = [];
d = flipud(d);
end
end
end
else
zsigma = [real(sigma); imag(sigma)];
arpackc( eupdfun, rvec, 'A', select, ...
zd, zv, ldv, zsigma, workev, ...
bmat, intconvert(n), whch, nev, tol, resid, ncv, zv, ...
ldv, iparam, ipntr, zworkd, workl, lworkl, ...
rwork, info );
if issymA
d = zd(1:2:end-1);
else
d = complex(zd(1:2:end-1),zd(2:2:end));
end
v = reshape(complex(zv(1:2:end-1),zv(2:2:end)),[n p]);
end
flag = processEUPDinfo(nargin<3);
if (issymA) || (~isrealprob)
if (nargout <= 1)
if isrealprob
varargout{1} = d;
else
varargout{1} = d(k:-1:1,1);
end
else
varargout{1} = v(:,1:k);
varargout{2} = diag(d(1:k,1));
if (nargout >= 3)
varargout{3} = flag;
end
end
else
if (nargout <= 1)
varargout{1} = d;
else
cplxd = find(di ~= 0);
% complex conjugate pairs of eigenvalues occur together
cplxd = cplxd(1:2:end);
v(:,[cplxd cplxd+1]) = [complex(v(:,cplxd),v(:,cplxd+1)) ...
complex(v(:,cplxd),-v(:,cplxd+1))];
varargout{1} = v(:,1:k);
varargout{2} = diag(d);
if (nargout >= 3)
varargout{3} = flag;
end
end
end
if (nargout >= 2) && (mode ~= 3) && ~isempty(B) && BisHpd == true
varargout{1} = RBsolve(varargout{1});
end
if ~isempty(B)
if nargout >= 2
varargout{2} = varargout{2}/scaleB;
else
varargout{1} = varargout{1}/scaleB;
end
end
if BisHpd == true && (nargout >= 2)
vnorms = zeros(k,1);
for ii = 1 : k
vnorms(ii) = scaleB*(varargout{1}(:,ii)'*(Bmtimes(varargout{1}(:,ii))));
varargout{1}(:,ii) = varargout{1}(:,ii)/sqrt(vnorms(ii));
end
end
cputms(4) = cputime-t0; % end timing post-processing
cputms(5) = sum(cputms(1:4)); % total time
if (eigs_display == 2)
printTimings;
end
%-------------------------------------------------------------------------%
% Nested functions
%-------------------------------------------------------------------------%
% checkInputs error checks the inputs to EIGS and also derives some
% variables from them:
% A may be a matrix or a function applying OP.
% Amatrix is true if A is a matrix, false if A is a function.
% isrealprob is true if all of A, B and sigma are real, false otherwise.
% issymA is true if A is symmetric, false otherwise.
% n is the size of (square) A and B.
% B is [] for the standard problem. Otherwise it may be one of B, CHOL(B)
% or CHOL(B(permB,permB)).
% classAB is single if either A or B is single, otherwise double.
% k is the number of eigenvalues to be computed.
% eigs_sigma is the value for sigma passed in by the user, 'LM' if it was
% unspecified. eigs_sigma may be either a string or a scalar value.
% whch is the ARPACK string corresponding to eigs_sigma and mode.
% sigma is the ARPACK scalar corresponding to eigs_sigma and mode.
% tol is the convergence tolerance.
% maxit is the maximum number of iterations.
% p is the number of Lanczos vectors.
% info is the start value, initialized to 1 or 0 to indicate whether to use
% resid as the start vector or not.
% eigs_display is true if Ritz values should be displayed, false otherwise.
% cholB is true if CHOL(B) was passed in instead of B, false otherwise.
% permB may be [], otherwise it is the permutation in CHOL(B(permB,permB)).
% resid is the start vector if specified and info=1, otherwise all zero.
% useeig is true if we need to use EIG instead of ARPACK, otherwise false.
% afunNargs is the range of EIGS' varargin that are to be passed as
% trailing parameters to the function as in afun(X,P1,P2,...).
function [A,Amatrix,isrealprob,issymA,n,B,classAB,k, ...
eigs_sigma,whch,sigma,tol,maxit,p,info,eigs_display,cholB,...
permB,resid,useeig,afunNargs,style,mode,Afactors,Bfactors] = checkInputs(varargin)
% Process inputs and do error-checking
% Process the input A or the inputs AFUN and N
% Start to derive some qualities (real, symmetric) about the problem
if isfloat(varargin{1})
A = varargin{1};
Amatrix = true;
else
% By checking the function A with fcnchk, we can now use direct
% function evaluation on the result, without resorting to feval
A = fcnchk(varargin{1});
Amatrix = false;
end
isrealprob = true;
issymA = false;
if Amatrix
isrealprob = isreal(A);
issymA = ishermitian(A);
[m,n] = size(A);
if (m ~= n)
error('MATLAB:eigs:NonSquareMatrixOrFunction',...
'A must be a square matrix or a function.')
end
else
n = varargin{2};
nstr = 'Size of problem, ''n'', must be a positive integer.';
if ~isscalar(n) || ~isreal(n)
error('MATLAB:eigs:NonPosIntSize', nstr)
end
if issparse(n)
n = full(n);
end
if (round(n) ~= n)
warning('MATLAB:eigs:NonPosIntSize',['%s\n ' ...
'Rounding input size.'],nstr)
n = round(n);
end
end
% Process the input B and derive the class of the problem.
% Is B present in the eigs call or not?
Bpresent = true;
Bstr = 'Generalized matrix B must be the same size as A.';
if (nargin < (3-Amatrix))
B = [];
Bpresent = false;
else
% Is the next input B or K?
B = varargin{3-Amatrix};
if ~isempty(B) % allow eigs(A,[],k,sigma,opts);
if isscalar(B)
if n ~= 1
% this input is really K and B is not specified
B = [];
Bpresent = false;
else
% This input could be B or K.
% If A is scalar, then the only valid value for k is 1.
% So if this input is scalar, let it be B, namely
% eigs(4,2,...) assumes A=4, B=2, NOT A=4, k=2
if ~isnumeric(B)
error('MATLAB:eigs:BsizeMismatchA', Bstr);
end
% Unless, of course, the scalar is 1, in which case
% assume the that it is meant to be K.
if (B == 1) && ((Amatrix && nargin <= 3) || ...
(~Amatrix && nargin <= 4))
B = [];
Bpresent = false;
elseif ~isfloat(B)
error('MATLAB:eigs:BsizeMismatchA', Bstr);
end
end
else
% B is a not a scalar.
if ~isfloat(B) || ~isequal(size(B),[n,n])
error('MATLAB:eigs:BsizeMismatchA', Bstr);
end
isrealprob = isrealprob && isreal(B);
end
end
end
% ARPACK can only handle homogeneous inputs
if Amatrix
classAB = superiorfloat(A,B);
A = cast(A,classAB);
B = cast(B,classAB);
else
if ~isempty(B)
classAB = class(B);
else
classAB = 'double';
end
end
% argOffset tells us where to get the eigs inputs K, SIGMA and OPTS.
% If A is really the function afun, then it also helps us find the
% trailing parameters in eigs(afun,n,[B],k,sigma,opts,P1,P2,...)
% Values of argOffset:
% 0: Amatrix is false and Bpresent is true:
% eigs(afun,n,B,k,sigma,opts,P1,P2,...)
% 1: Amatrix and Bpresent are both true, or both false
% eigs(A,B,k,sigma,opts)
% eigs(afun,n,k,sigma,opts,P1,P2,...)
% 2: Amatrix is true and Bpresent is false:
% eigs(A,k,sigma,opts)
argOffset = Amatrix + ~Bpresent;
if Amatrix && ((nargin - Bpresent)>4)
error('MATLAB:eigs:TooManyInputs', 'Too many inputs.')
end
% Process the input K.
if (nargin < (4-argOffset))
k = min(n,6);
else
k = varargin{4-argOffset};
kstr = ['Number of eigenvalues requested, k, must be a' ...
' positive integer <= n.'];
if ~isnumeric(k) || ~isscalar(k) || ~isreal(k) || (k>n)
error('MATLAB:eigs:NonIntegerEigQty', kstr)
end
if issparse(k)
k = full(k);
end
if (round(k) ~= k)
warning('MATLAB:eigs:NonIntegerEigQty',['%s\n ' ...
'Rounding number of eigenvalues.'],kstr)
k = round(k);
end
end
% Process the input SIGMA and derive ARPACK values whch and sigma.
% eigs_sigma is the value documented in the help as "SIGMA" that is
% passed in to EIGS. eigs_sigma may be either a scalar, including 0,
% or a string, including 'SM'.
% In ARPACK, eigs_sigma corresponds to two variables:
% 1. which, called "whch" to avoid conflict with MATLAB's function
% 2. sigma
% whch is always a string. sigma is always a scalar.
% Valid combinations are shown below. Note eigs_sigma = 0/'SM' has
% the same sigma/whch values as eigs_sigma='LM' (default) so these
% must be distinguished by the mode.
% eigs_sigma = 'SM' or 0 => sigma = 0, whch = 'LM' (mode=3)
% eigs_sigma is a string not 'SM' => sigma = 0, whch = eigs_sigma (mode=1)
% eigs_sigma is any scalar => sigma = eigs_sigma, whch = 'LM'
% (mode=1)
whchstr = 'Eigenvalue range sigma must be a valid 2-element string.';
if (nargin < (5-argOffset))
% default: eigs 'LM' => ARPACK which='LM', sigma=0
eigs_sigma = 'LM';
whch = 'LM';
sigma = 0;
else
eigs_sigma = varargin{5-argOffset};
if ischar(eigs_sigma)
% eigs(string) => ARPACK which=string, sigma=0
if ~isequal(size(eigs_sigma),[1,2])
error('MATLAB:eigs:EigenvalueRangeNotValid', ...
[whchstr '\nFor real symmetric A, the' ...
' choices are ''%s'', ''%s'', ''%s'', ''%s'' or ''%s''.' ...
'\nFor non-symmetric or complex' ...
' A, the choices are ''%s'', ''%s'', ''%s'', ''%s'',' ...
' ''%s'' or ''%s''.\n'], ...
'LM','SM','LA','SA','BE','LM','SM','LR','SR','LI','SI')
end
eigs_sigma = upper(eigs_sigma);
if strcmp(eigs_sigma,'SM')
% eigs('SM') => ARPACK which='LM', sigma=0
whch = 'LM';
else
% eigs(string), where string~='SM' => ARPACK which=string, sigma=0
whch = eigs_sigma;
end
sigma = zeros(classAB);
else
% eigs(scalar) => ARPACK which='LM', sigma=scalar
if ~isfloat(eigs_sigma) || ~isscalar(eigs_sigma)
error('MATLAB:eigs:EigenvalueShiftNonScalar',...
'Eigenvalue shift sigma must be a scalar.')
end
sigma = eigs_sigma;
if issparse(sigma)
sigma = full(sigma);
end
sigma = cast(sigma,classAB);
isrealprob = isrealprob && isreal(sigma);
whch = 'LM';
end
end
% Process the input OPTS and derive some ARPACK values.
% ARPACK's minimum tolerance is eps/2 ([S/D]LAMCH's EPS)
tol = eps(classAB);
maxit = [];
p = [];
style = [];
% Always use resid as the start vector, whether it is OPTS.v0 or
% randomly generated within eigs. We default resid to empty here.
% If the user does not initialize it, we provide a random residual
% below.
info = intconvert(1);
resid = [];
eigs_display = 1;
cholB = false; % do we have B or its Cholesky factor?
permB = []; % if cholB, is it chol(B), or chol(B(permB,permB))?
if (nargin >= (6-argOffset))
opts = varargin{6-argOffset};
if ~isa(opts,'struct')
error('MATLAB:eigs:OptionsNotStructure',...
'Options argument must be a structure.')
end
if isfield(opts,'issym') && ~Amatrix
issymA = opts.issym;
if (issymA ~= false) && (issymA ~= true)
error('MATLAB:eigs:InvalidOptsIssym', ...
'opts.issym must be true or false.')
end
end
if isfield(opts,'isreal') && ~Amatrix
if (opts.isreal ~= false) && (opts.isreal ~= true)
error('MATLAB:eigs:InvalidOptsIsreal', ...
'opts.isreal must be true or false.')
end
isrealprob = isrealprob && opts.isreal;
end
if ~isempty(B) && (isfield(opts,'cholB') || isfield(opts,'permB'))
if isfield(opts,'cholB')
cholB = opts.cholB;
if (cholB ~= false) && (cholB ~= true)
error('MATLAB:eigs:InvalidOptsCholB', ...
'opts.cholB must be true or false.')
end
if isfield(opts,'permB')
if issparse(B) && cholB
permB = opts.permB;
if ~isvector(permB) || ~isequal(sort(permB(:)),(1:n)')
error('MATLAB:eigs:InvalidOptsPermB',...
'opts.permB must be a permutation of 1:n.')
end
else
warning('MATLAB:eigs:IgnoredOptionPermB', ...
['Ignoring opts.permB since B is not its sparse' ...
' Cholesky factor.'])
end
end
end
end
if isfield(opts,'tol')
if ~isfloat(tol) || ~isscalar(opts.tol) || ~isreal(opts.tol) || (opts.tol<=0)
error('MATLAB:eigs:InvalidOptsTol',...
['Convergence tolerance opts.tol must be a strictly' ...
' positive real scalar.'])
end
tol = cast(full(opts.tol),classAB);
end
if isfield(opts,'p')
p = opts.p;
pstr = ['Number of basis vectors opts.p must be a positive' ...
' integer <= n.'];
if ~isnumeric(p) || ~isscalar(p) || ~isreal(p) || (p<=0) || (p>n)
error('MATLAB:eigs:InvalidOptsP', pstr)
end
if issparse(p)
p = full(p);
end
if (round(p) ~= p)
warning('MATLAB:eigs:NonIntegerVecQty',['%s\n ' ...
'Rounding number of basis vectors.'],pstr)
p = round(p);
end
end
if isfield(opts,'maxit')
maxit = opts.maxit;
str = ['Maximum number of iterations opts.maxit must be' ...
' a positive integer.'];
if ~isnumeric(maxit) || ~isscalar(maxit) || ~isreal(maxit) || (maxit<=0)
error('MATLAB:eigs:OptsMaxitNotPosInt', str)
end
if issparse(maxit)
maxit = full(maxit);
end
if (round(maxit) ~= maxit)
warning('MATLAB:eigs:NonIntegerIterationQty',['%s\n ' ...
'Rounding number of iterations.'],str)
maxit = round(maxit);
end
end
if isfield(opts,'v0')
if ~isfloat(opts.v0) || ~isequal(size(opts.v0),[n,1])
error('MATLAB:eigs:WrongSizeOptsV0',...
'Start vector opts.v0 must be n-by-1.')
end
if isrealprob
if ~isreal(opts.v0)
error('MATLAB:eigs:NotRealOptsV0',...
'Start vector opts.v0 must be real for real problems.')
end
resid(1:n,1) = full(opts.v0);
else
resid(2:2:2*n,1) = full(imag(opts.v0));
resid(1:2:(2*n-1),1) = full(real(opts.v0));
end
end
if isfield(opts,'disp')
eigs_display = opts.disp;
dispstr = 'Diagnostic level opts.disp must be an integer.';
if ~isnumeric(eigs_display) || ~isscalar(eigs_display) || ...
~isreal(eigs_display) || (eigs_display<0)
error('MATLAB:eigs:NonIntegerDiagnosticLevel', dispstr)
end
if (round(eigs_display) ~= eigs_display)
warning('MATLAB:eigs:NonIntegerDiagnosticLevel', ...
'%s\n Rounding diagnostic level.',dispstr)
eigs_display = round(eigs_display);
end
end
if isfield(opts,'cheb')
error('MATLAB:eigs:ObsoleteOptionCheb', ...
'Polynomial acceleration opts.cheb is an obsolete option.');
end
if isfield(opts,'stagtol')
error('MATLAB:eigs:ObsoleteOptionStagtol', ...
'Stagnation tolerance opts.stagtol is an obsolete option.');
end
if isfield(opts,'style')
style = opts.style;
str = 'style must be ''S'' or ''G''.';
if ~ischar(style)
error('MATLAB:eigs:InvalidStyle',str);
elseif ~(strcmp(style,'S') || strcmp(style,'G'))
error('MATLAB:eigs:InvalidStyle',str);
end
end
end
if (isempty(resid))
if isrealprob
resid = cast(rand(n,1),classAB);
else
resid = cast(rand(2*n,1),classAB);
end
end
afunNargs = zeros(1,0);
if ~Amatrix
% The trailing parameters for afun start at varargin{7-argOffset}
% in eigs(afun,n,[B],k,sigma,opts,P1,P2,...). If there are no
% trailing parameters in eigs, then afunNargs is a 1-by-0 empty
% and no trailing parameters are passed to afun(x)
afunNargs = 7-argOffset:nargin;
end
% Now that OPTS has been processed, do final error checking and
% assign ARPACK variables
% Extra check on input B
if ~isempty(B)
% B must be symmetric (Hermitian) positive (semi-)definite
if cholB
if ~isequal(triu(B),B)
error('MATLAB:eigs:BNotChol', ...
'opts.CHOLB specified, but B is not upper triangular.');
end
end
end
if isempty(style)
if strcmp(eigs_sigma,'SM') || isscalar(eigs_sigma) || ~isempty(B)
style = 'G';
else
style = 'S';
end
end
if ~isempty(B)
scaleB = norm(B,'fro')/sqrt(n);
scaleB = 2^(floor(log2(scaleB+1)));
B = B/scaleB;
if cholB
scaleB = scaleB^2;
end
if isscalar(eigs_sigma)
sigma = scaleB*eigs_sigma;
end
end
if strcmp(eigs_sigma,'SM') || ~ischar(eigs_sigma)
% eigs(A,B,k,scalarSigma) or eigs(A,B,k,'SM'), B may be []
% Note: sigma must be real for [s,d]saupd and [s,d]naupd
% If sigma is complex, even if A and B are both real, we use
% [c,z]naupd.
% This means that mode=3 in [s,d]naupd, which has
% OP = real(inv(A - sigma*M)*M) and B = M
% reduces to the same OP as [s,d]saupd and [c,z]naupd.
% A*x = lambda*M*x, M symmetric (positive) semi-definite
% => OP = inv(A - sigma*M)*M and B = M
% => shift-and-invert mode
mode = 3;
elseif strcmp(style,'S')
% eigs(A,k,stringSigma) or eigs(A,[],k,stringSigma),
% stringSigma~='SM'
% A*x = lambda*x
% => OP = A and B = I
mode = 1;
else
% eigs(A,B,k,stringSigma), stringSigma~='SM'
% A*x = lambda*B*x
% => OP = inv(B)*A and use standard inner product.
mode = 2;
end
BisHpd = false;
if cholB || (~isempty(B) && ishermitian(B))
% The reordering permutation permB is [] unless B is sparse
[RB,RBT,permB,BisHpd] = CHOLfactorB;
if mode == 3 && ~cholB
RB = []; RBT = []; permB = [];
end
end
qqB = [];
if BisHpd == false && (mode == 1 || mode == 2)
[LB,UB,ppB,qqB,dgB] = LUfactorB;
end
Bfactors = [];
if ~isempty(B)
if BisHpd == true
Bfactors = struct('RB',RB,'RBT',RBT,'permB',permB,'BisHpd',BisHpd);
elseif (mode == 1 || mode == 2)
Bfactors = struct('LB',LB,'UB',UB,'ppB',ppB,'qqB',qqB,'dgB',dgB,'BisHpd',BisHpd);
end
end
Afactors = [];
qq = [];
if (mode == 3) && Amatrix % need lu(A-sigma*B)
% The reordering permutation permAsB is [] unless A-sigma*B is sparse
[L,U,pp,qq,dgAsB] = LUfactorAminusSigmaB;
Afactors = struct('L',L,'U',U,'pp',pp,'qq',qq,'dgAsB',dgAsB);
end % if (mode == 3) && Amatrix
% under these conditions, OP must be unsymmetric
% note that OP = inv(A-\sigma*B)*B IS symmetric if A is symmetric
% and B-inner product is used!
if ~isempty(B) && (BisHpd == false || (strcmp(style,'S') && mode == 3))
issymA = false;
end
% Extra check on input K
% We fall back on using the full EIG code if K is too large.
useeig = false;
if isrealprob && issymA
knstr = sprintf(['For real symmetric problems, must have' ...
' number of eigenvalues k < n.\n']);
else
knstr = sprintf(['For nonsymmetric and complex problems,' ...
' must have number of eigenvalues k < n-1.\n']);
end
if isempty(B)
knstr = [knstr 'Using eig(full(A)) instead.'];
else
knstr = [knstr 'Using eig(full(A),full(B)) instead.'];
end
if (k == 0)
useeig = true;
end
if isrealprob && issymA
if (k > n-1)
if (n >= 6)
warning('MATLAB:eigs:TooManyRequestedEigsForRealSym', ...
'%s',knstr)
end
useeig = true;
end
else
if (k > n-2)
if (n >= 7)
warning('MATLAB:eigs:TooManyRequestedEigsForComplexNonsym', ...
'%s',knstr)
end
useeig = true;
end
end
% Extra check on input SIGMA
if isrealprob && issymA
if ~isreal(sigma)
error('MATLAB:eigs:ComplexShiftForRealSymProblem',...
['For real symmetric problems, eigenvalue shift sigma must' ...
' be real.'])
end
else
if ~isrealprob && issymA && ~isreal(sigma)
warning('MATLAB:eigs:ComplexShiftForHermitianProblem', ...
['Complex eigenvalue shift sigma on a Hermitian problem' ...
' (all real eigenvalues).'])
end
end
if isrealprob && issymA
if strcmp(whch,'LR')
whch = 'LA';
warning('MATLAB:eigs:SigmaChangedToLA', ...
['For real symmetric problems, sigma value ''LR''' ...
' (Largest Real) is now ''LA'' (Largest Algebraic).'])
end
if strcmp(whch,'SR')
whch = 'SA';
warning('MATLAB:eigs:SigmaChangedToSA', ...
['For real symmetric problems, sigma value ''SR''' ...
' (Smallest Real) is now ''SA'' (Smallest Algebraic).'])
end
if ~ismember(whch,{'LM', 'SM', 'LA', 'SA', 'BE'})
error('MATLAB:eigs:EigenvalueRangeNotValid', ...
[whchstr '\nFor real symmetric A, the' ...
' choices are ''%s'', ''%s'', ''%s'', ''%s'' or ''%s''.'], ...
'LM','SM','LA','SA','BE');
end
else
if strcmp(whch,'BE')
warning('MATLAB:eigs:SigmaChangedToLM', ...
['Sigma value ''BE'' is now only available for real' ...
' symmetric problems. Computing ''LM'' eigenvalues instead.'])
whch = 'LM';
end
if ~ismember(whch,{'LM', 'SM', 'LR', 'SR', 'LI', 'SI'})
error('MATLAB:eigs:EigenvalueRangeNotValid', ...
[whchstr '\nFor non-symmetric or complex' ...
' A, the choices are ''%s'', ''%s'', ''%s'', ''%s'',' ...
' ''%s'' or ''%s''.\n'],'LM','SM','LR','SR','LI','SI');
end
end
% The remainder of the error checking does not apply for the large
% values of K that force us to use full EIG instead of ARPACK.
if useeig
return
end