-
Notifications
You must be signed in to change notification settings - Fork 2
/
iva_second_orderOriginal.m
1523 lines (1390 loc) · 46.5 KB
/
iva_second_orderOriginal.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 [W,cost,Sigma_N,isi] = iva_second_order(X,varargin)
% [W,cost,Sigma_N,isi] = iva_second_order(X,varargin)
%
% Implementations of all the second-order (Gaussian) independent vector
% analysis (IVA) algorithms. Namely real-valued and complex-valued with
% circular and non-circular using gradient, Newton, and quasi-Newton
% optimizations.
%
% Input:
% X - data observations from K data sets, i.e. X{k}=A{k}*S{k}, where A{k}
% is an N x N unknowned invertible mixing matrix and S{k} is N x T matrix
% with the nth row corresponding to T samples of the nth source in the kth
% dataset. For IVA it is assumed that the source is statistically
% independent of all the sources within a dataset and exactly dependent on
% at most one source in each of the other datasets. The data, X, can be
% either a cell array as indicated or a 3-dimensional matrix of dimensions
% N x T x K. The latter enforces the assumption of an equal number of
% samples in each dataset.
%
% Output:
% W - the estimated demixing matrices so that ideally W{k}*A{k} = P*D{k}
% where P is any arbitrary permutation matrix and D{k} is any diagonal
% invertible (scaling) matrix. Note P is common to all datasets; this is
% to indicate that the local permuation ambiguity between dependent sources
% across datasets should ideally be resolved by IVA.
%
% cost - the cost for each iteration
%
% isi - joint inter-symbol-interference is available if user supplies true
% mixing matrices for computing a performance metric
%
% Optional input pairs and default values are given in list below:
%
% 'opt_approach','newton', ... % optimization type: gradient, (newton), quasi
% 'complex_valued',false, ... % if any input is complex or quasi approach used then setting is forced to true
% 'circular',false, ... % set to true to only consider circular for complex-valued cost function
% 'whiten',true, ... % whitening is optional (except for quasi approach it is required)
% 'verbose',false, ... % verbose true enables print statements
% 'A',[], ... % true mixing matrices A, automatically sets verbose
% 'W_init',[], ... % initial estimates for demixing matrices in W
% 'jdiag_initW',false, ... % use CCA (K=2) or joint diagonalization (K>2)
% 'maxIter',512, ... % max number of iterations
% 'WDiffStop',1e-6, ... % stopping criterion
% 'alpha0',1.0 ... % initial step size scaling (will be doubled for complex-valued)
%
% Example call:
% W=iva_second_order(X,'opt_approach','newton','circular',true)
%
% Given that X is complex-valued this uses Newton optimization for circular
% Gaussian IVA cost function. If the last argument is set to false then
% the cost-function is the more general non-circular Gaussian IVA cost
% function.
%
% To test code call function with no input arguments: iva_second_order
%
% Coded by Matthew Anderson (matt.anderson at umbc.edu)
%
% References:
%
% [1] M. Anderson, X.-L. Li, & T. Adalı, "Nonorthogonal Independent Vector Analysis Using Multivariate Gaussian Model," LNCS: Independent Component Analysis and Blind Signal Separation, Latent Variable Analysis and Signal Separation, Springer Berlin / Heidelberg, 2010, 6365, 354-361
% [2] M. Anderson, T. Adalı, & X.-L. Li, "Joint Blind Source Separation of Multivariate Gaussian Sources: Algorithms and Performance Analysis," IEEE Trans. Signal Process., 2012, 60, 1672-1683
% [3] M. Anderson, X.-L. Li, & T. Adalı, "Complex-valued Independent Vector Analysis: Application to Multivariate Gaussian Model," Signal Process., 2012, 1821-1831
% Version 01 - 20120913 - Initial publication
% Version 02 - 20120919 - Using decouple_trick function, bss_isi, whiten, &
% cca subfunctions
global JBSS_SOS_EXIST
if isempty(JBSS_SOS_EXIST)
JBSS_SOS_EXIST=exist('jbss_sos.m','file');
end
if nargin==0
help iva_second_order
test_iva_second_order
return
end
%% Gather Options
% build default options structure
options=struct( ...
'opt_approach','newton', ... % optimization type: gradient, (newton), quasi
'complex_valued',false, ... % if any input is complex or quasi approach used then setting is forced to true
'circular',false, ... % set to true to only consider circular for complex-valued cost function
'whiten',true, ... % whitening is optional (except for quasi approach it is required)
'verbose',false, ... % verbose true enables print statements
'A',[], ... % true mixing matrices A, automatically sets verbose
'W_init',[], ... % initial estimates for demixing matrices in W
'jdiag_initW',false, ... % use CCA (K=2) or joint diagonalization (K>2)
'maxIter',512, ... % max number of iterations
'WDiffStop',1e-6, ... % stopping criterion
'alpha0',1.0 ... % initial step size scaling (will be doubled for complex-valued)
);
% load in user supplied options
options=getopt(options,varargin{:});
supplyA=~isempty(options.A); % set to true if user has supplied true mixing matrices
blowup = 1e3;
alphaScale=0.9; % alpha0 to alpha0*alphaScale when cost does not decrease
alphaMin=options.WDiffStop; % alpha0 will max(alphaMin,alphaScale*alpha0)
outputISI=false;
opt_approach=find(strcmp(options.opt_approach, ...
{'gradient','newton','quasi'}),1); % 1='gradient', 2='newton', 3='quasi'
options.whiten=(options.whiten || (opt_approach==3)); % whitening required for real-valued quasi & complex-valued gradient approach
%% Create cell versions
% Faster than using the more natural 3-dimensional version
if iscell(options.A)
K=length(options.A);
A=zeros([size(options.A{1}) K]);
for k=1:K
A(:,:,k)=options.A{k};
end
options.A=A;
options.complex_valued = options.complex_valued || any(imag(A(:)));
clear A
end
if ~iscell(X)
options.complex_valued = options.complex_valued || any(imag(X(:)));
options.whiten = options.whiten || (options.complex_valued && opt_approach==1);
if options.whiten
[X,V]=whiten(X);
end
[N,T,K]=size(X); % the input format insures all datasets have equal number of samples
Rx=cell(K,K);
for k1=1:K
Rx{k1,k1}=1/T*(X(:,:,k1)*X(:,:,k1)');
for k2=(k1+1):K
Rx{k1,k2}=1/T*(X(:,:,k1)*X(:,:,k2)');
Rx{k2,k1}=Rx{k1,k2}';
end
end
if options.complex_valued && ~options.circular
% complex-valued non-circular cost
% compute data pseudo cross-covariance matrices
Px=cell(K,K);
for k1=1:K
Px{k1,k1}=1/T*(X(:,:,k1)*X(:,:,k1).');
for k2=(k1+1):K
Px{k1,k2}=1/T*(X(:,:,k1)*X(:,:,k2).');
Px{k2,k1}=Px{k1,k2}.';
end % k2
end % k1
end
else % iscell
[rowX,colX]=size(X);
% then this is cell array with each entry being X{k} being a dataset
% for now assume N is fixed
X=X(:);
K=max(colX,rowX);
[N,T]=size(X{1});
if ~options.complex_valued
for k=1:K
if T~=size(X{k},2)
error('Each dataset must have the same number of samples.')
end
options.complex_valued = options.complex_valued || any(imag(X{k}(:)));
if options.complex_valued
break
end
end % k
end
options.whiten = options.whiten || (options.complex_valued && opt_approach==1);
if options.whiten
[X,V_cell]=whiten(X);
V=zeros(N,N,K);
for k=1:K
V(:,:,k)=V_cell{k};
end
clear V_cell
end
Rx=cell(K,K);
for k1=1:K
options.complex_valued = options.complex_valued || any(imag(X{k1}(:)));
Rx{k1,k1}=1/T*(X{k1}*X{k1}');
for k2=(k1+1):K
Rx{k1,k2}=1/T*(X{k1}*X{k2}');
Rx{k2,k1}=Rx{k1,k2}';
end
end
if options.complex_valued && ~options.circular
% complex-valued non-circular cost
% compute data pseudo cross-covariance matrices
Px=cell(K,K);
for k1=1:K
Px{k1,k1}=1/T*(X{k1}*X{k1}.');
for k2=(k1+1):K
Px{k1,k2}=1/T*(X{k1}*X{k2}.');
Px{k2,k1}=Px{k1,k2}.';
end % k2
end % k1
end
end
%% Initialize W
if ~isempty(options.W_init)
W=options.W_init;
if ~options.complex_valued && any(imag(W(:))) && opt_approach==1
warning(['Supplied initial W is complex valued and ' ...
'gradient option approach is set; ' ...
'need to set whitening option to true for best performance.']) %#ok<WNTAG>
end
if size(W,3)==1 && size(W,1)==N && size(W,2)==N
W=repmat(W,[1,1,K]);
end
if options.whiten
for k=1:K
W(:,:,k)=W(:,:,k)/V(:,:,k);
end
end
else
if options.jdiag_initW
if K>2
% initialize with multi-set diagonalization (orthogonal solution)
% Assume N is same for all K datasets
if ~JBSS_SOS_EXIST
error('To use this option requires another package.')
end
W=jbss_sos(X,0,'whole');
else % if K==2 then CCA is sufficient (should be few to no iterations required)
W_cell=cca(X);
W=zeros(N,N,K);
for k=1:K
W(:,:,k)=W_cell{k};
end
end
else % randomly initialize
W=randn(N,N,K);
if options.complex_valued
W=W+1j*randn(N,N,K);
end
for k = 1:K
W(:,:,k)=(sqrtm(W(:,:,k)*W(:,:,k)'))\W(:,:,k);
end
end
end
%% When mixing matrix A supplied
% verbose is set to true
% outputISI can be computed if requested
% A matrix is conditioned by V if data is whitened
if supplyA
% only reason to supply A matrices is to display running performance
options.verbose=true;
if nargout>3
outputISI=true;
isi=zeros(1,options.maxIter);
end
if options.whiten
for k = 1:K
options.A(:,:,k) = V(:,:,k)*options.A(:,:,k);
end
end
end
%% Check rank of data-covariance matrix
% should be full rank, if not we inflate
% this is ad hoc and no robustness is assured by diagonal loading procedure
Rxall=cell2mat(Rx);
r=rank(Rxall);
if r<(N*K)
% inflate Rx
eigRx=svd(Rxall);
Rxall=Rxall+eigRx(r)*eye(N*K); %diag(linspace(0.1,0.9,N*K)); % diagonal loading
Rx=mat2cell(Rxall,N*ones(K,1),N*ones(K,1));
end
%% Initialize some local variables
cost=zeros(1,options.maxIter);
cost_const=K*log(2*pi*exp(1)); % local constant
%% Initializations based on real vs complex-valued
if options.complex_valued
grad=complex(zeros(N,K));
if opt_approach==2
HA=zeros(N*K,N*K);
end
% Double step-size for complex-valued gradient optimization
if opt_approach==1
options.alpha0 = 2*options.alpha0;
end
else % real-valued
grad=zeros(N,K);
if opt_approach==2
H=zeros(N*K,N*K);
end
end
%% Main Iteration Loop
for iter = 1:options.maxIter
termCriterion=0;
% Some additional computations of performance via ISI when true A is supplied
if supplyA
[amari_avg_isi,amari_joint_isi]=bss_isi(W,options.A);
if outputISI
isi(iter)=amari_joint_isi;
end
end
W_old=W; % save current W as W_old
cost(iter)=0;
for k=1:K
cost(iter)=cost(iter)-log(abs(det(W(:,:,k))));
end
Q=0; R=0;
%% Loop over each SCV
for n=1:N
Wn=W(n,:,:);
Wn=conj(Wn(:));
% Efficient version of Sigma_n=Yn*Yn'/T;
Sigma_n=eye(K); %
for k1=1:K
for k2=k1:K
Sigma_n(k1,k2)=W(n,:,k1)*Rx{k1,k2}*W(n,:,k2)';
if k1~=k2
Sigma_n(k2,k1)=Sigma_n(k1,k2)';
end
end % k2
end %k1
if options.complex_valued && ~options.circular
% complex-valued non-circular cost
% compute SCV pseudo cross-covariance matrices
SigmaP_n=zeros(K); % pseudo = Yn*Yn.'/T;
for k1=1:K
for k2=k1:K
SigmaP_n(k1,k2)=W(n,:,k1)*Px{k1,k2}*W(n,:,k2).';
if k1~=k2
SigmaP_n(k2,k1)=SigmaP_n(k1,k2);
end
end % k2
end %k1
Sigma_Total=[Sigma_n SigmaP_n; SigmaP_n' conj(Sigma_n)];
cost(iter)=cost(iter)+0.5*log(det(Sigma_Total));
else
cost(iter)=cost(iter)+0.5*(cost_const+log(det(Sigma_n)));
end
if options.complex_valued && ~options.circular
inv_Sigma_n=inv(Sigma_Total);
P=inv_Sigma_n(1:K,1:K);
Pt=inv_Sigma_n(1:K,K+(1:K));
else
inv_Sigma_n=inv(Sigma_n);
end
[hnk,Q,R]=decouple_trick(W,n,Q,R);
for k=1:K
% Analytic derivative of cost function with respect to vn
% Code below is efficient implementation of computing the gradient, that is
% independent of T
grad(:,k)=-hnk(:,k)/(W(n,:,k)*hnk(:,k));
if options.complex_valued && ~options.circular
for kk=1:K
grad(:,k)=grad(:,k)+ ...
Rx{k,kk}*W(n,:,kk)'*P(k,kk)'+Px{k,kk}*W(n,:,kk).'*Pt(k,kk)';
end
else
for kk=1:K
grad(:,k)=grad(:,k)+ ...
Rx{k,kk}*W(n,:,kk)'*inv_Sigma_n(kk,k);
end
end
if opt_approach==1 || ... % real/complex gradient
(opt_approach==3 && ~options.complex_valued) % real quasi newton
wnk=W(n,:,k)';
if opt_approach==1
gradNorm=vecnorm(grad(:,k)); % normalize gradient
gradNormProj=vecnorm(gradNorm-wnk'*gradNorm*wnk); % non-colinear direction normalized
W(n,:,k)=vecnorm(wnk-options.alpha0*gradNormProj)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% The following computations are potentially unnecessary
%%%%% see that the quasi-newton approach does not do this
%%%%% step.
for kk=1:K
Sigma_n(k,kk)=W(n,:,k)*Rx{k,kk}*W(n,:,kk)'; % = Yn*Yn'/T;
end
Sigma_n(:,k)=Sigma_n(k,:)';
if options.complex_valued && ~options.circular
for kk=1:K
SigmaP_n(k,kk)=W(n,:,k)*Px{k,kk}*W(n,:,kk).'; % = Yn*Yn.'/T
end
SigmaP_n(:,k)=SigmaP_n(k,:).';
Sigma_Total=[Sigma_n SigmaP_n; SigmaP_n' conj(Sigma_n)];
inv_Sigma_n=inv(Sigma_Total);
else
inv_Sigma_n=inv(Sigma_n);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif opt_approach==3 % real-valued quasi-newton (block newton)
% Hessian inverse computed using matrix inversion lemma
Hinv=1/inv_Sigma_n(k,k)*(eye(N) - ...
hnk(:,k)*hnk(:,k)'/(inv_Sigma_n(k,k)+1/(hnk(:,k)'*wnk)^2));
% Block-Newton update of Wnk
W(n,:,k)=vecnorm(wnk-options.alpha0*(Hinv*grad(:,k)))';
end
end
end % k
if opt_approach==2 || (opt_approach==3 && options.complex_valued)
%% Compute SCV Hessian
for k1=1:K
if options.complex_valued
if opt_approach==2 % complex-valued Newton
HA((k1-1)*N+(1:N),(k1-1)*N+(1:N)) = ...
conj(hnk(:,k1))*hnk(:,k1)'/(hnk(:,k1)'*W(n,:,k1)')^2;
if ~options.circular % complex-valued Newton non-circular
HA((k1-1)*N+(1:N),(k1-1)*N+(1:N)) = ...
HA((k1-1)*N+(1:N),(k1-1)*N+(1:N)) + ...
Pt(k1,k1)*conj(Px{k1,k1});
end
end
H((k1-1)*N+(1:N),(k1-1)*N+(1:N)) = ...
conj(inv_Sigma_n(k1,k1)*Rx{k1,k1});
else % real-valued Newton
H((k1-1)*N+(1:N),(k1-1)*N+(1:N)) = ...
inv_Sigma_n(k1,k1)*Rx{k1,k1} + ...
hnk(:,k1)*hnk(:,k1)'/(hnk(:,k1)'*W(n,:,k1)')^2;
end
for k2=(k1+1):K
if opt_approach==2 && options.complex_valued && ~options.circular
% complex-valued Newton non-circular
HA((k1-1)*N+(1:N),(k2-1)*N+(1:N)) = ...
Pt(k2,k1)*conj(Px{k1,k2});
HA((k2-1)*N+(1:N),(k1-1)*N+(1:N)) = ...
Pt(k1,k2)*conj(Px{k2,k1});
Hs=conj(P(k2,k1)*Rx{k1,k2});
else
Hs=inv_Sigma_n(k1,k2)*Rx{k2,k1}.';
end
H((k1-1)*N+(1:N),(k2-1)*N+(1:N))=Hs;
H((k2-1)*N+(1:N),(k1-1)*N+(1:N))=Hs';
end % k2
end % k1
%% Alternative approach to calculating H
% H=kron(inv_Sigma_n,ones(N)).*Rxall;
% for k=1:K
% H((k-1)*N+(1:N),(k-1)*N+(1:N))=H((k-1)*N+(1:N),(k-1)*N+(1:N)) + ...
% hnk(:,k)*hnk(:,k)'/(hnk(:,k)'*W(n,:,k)')^2;
% end
%% Newton Update
if ~options.complex_valued % real-valued Newton
Wn=Wn-options.alpha0*(H\grad(:)); % much faster inv(H)*grad(:)
else % complex-valued
if opt_approach == 2 % complex-valued Newton
% improve stability by using 0.99 in Hessian
Wn=Wn-options.alpha0*(conj(H)-0.99*conj(HA)*(H\HA))\(grad(:)-conj(HA)*(H\conj(grad(:))));
elseif opt_approach == 3 % complex-valued Quasi-Newton
Wn=Wn-options.alpha0*conj(H)\grad(:);
else
error('Should not happen.')
end
Wn=conj(Wn);
end
%% Store Updated W
Wn=(reshape(Wn,N,K));
for k=1:K
W(n,:,k)=vecnorm(Wn(:,k)).';
end % k
end % opt_approach==2 || (opt_approach==3 && options.complex_valued)
end %n
for k=1:K
termCriterion = max(termCriterion,max(1-abs(diag(W_old(:,:,k)*W(:,:,k)'))));
end % k
%% Decrease step size alpha if cost increased from last iteration
if iter>1
if cost(iter)>cost(iter-1)
options.alpha0=max(alphaMin,alphaScale*options.alpha0);
end
end
%% Check the termination condition
if termCriterion < options.WDiffStop || iter == options.maxIter
break;
elseif termCriterion > blowup || isnan(cost(iter))
for k = 1:K
W(:,:,k) = eye(N) + 0.1*randn(N);
end
if options.verbose
fprintf('\n W blowup, restart with new initial value.');
end
end
%% Display Iteration Information
if options.verbose
if supplyA
fprintf('\n Step %d: W change: %f, Cost: %f, Avg ISI: %f, Joint ISI: %f', ...
iter, termCriterion,cost(iter),amari_avg_isi,amari_joint_isi);
else
fprintf('\n Step %d: W change: %f, Cost: %f', iter, termCriterion,cost(iter));
end
end % options.verbose
end % iter
%% Finish Display
if iter==1 && options.verbose
if supplyA
fprintf('\n Step %d: W change: %f, Cost: %f, Avg ISI: %f, Joint ISI: %f', ...
iter, termCriterion,cost(iter),amari_avg_isi,amari_joint_isi);
else
fprintf('\n Step %d: W change: %f, Cost: %f', iter, termCriterion,cost(iter));
end
end % options.verbose
if options.verbose
fprintf('\n');
end
%% Clean-up Outputs
cost=cost(1:iter);
if outputISI
isi=isi(1:iter);
end
if options.whiten
for k=1:K
W(:,:,k)=W(:,:,k)*V(:,:,k);
end
else % no prewhitening
%% Scale demixing vectors to generate unit variance sources
for n=1:N
for k=1:K
W(n,:,k)=W(n,:,k)/sqrt(W(n,:,k)*Rx{k,k}*W(n,:,k)');
end
end
end
%% Resort order of SCVs
% Order the components from most to least ill-conditioned
% First, compute the data covariance matrices (by undoing any whitening)
if options.whiten
for k1=1:K
Rx{k1,k1}=(V(:,:,k1)\Rx{k1,k1})/V(:,:,k1)';
for k2=(k1+1):K
Rx{k1,k2}=(V(:,:,k1)\Rx{k1,k2})/V(:,:,k2)';
Rx{k2,k1}=Rx{k1,k2}';
end % k2
end % k1
end
% Second, compute the determinant of the SCVs
detSCV=zeros(1,N);
Sigma_N=zeros(K,K,N);
for n=1:N
% Efficient version of Sigma_n=Yn*Yn'/T;
Sigma_n=zeros(K); %
for k1=1:K
for k2=k1:K
Sigma_n(k1,k2)=W(n,:,k1)*Rx{k1,k2}*W(n,:,k2)';
Sigma_n(k2,k1)=Sigma_n(k1,k2)';
end % k2
end %k3
Sigma_N(:,:,n)=Sigma_n;
if any(imag(Sigma_n(:))~=0) && ~options.circular && false
SigmaP_n=zeros(K); % pseudo = Yn*Yn.'/T;
for k1=1:K
for k2=k1:K
SigmaP_n(k1,k2)=W(n,:,k1)*Px{k1,k2}*W(n,:,k2).';
if k1~=k2
SigmaP_n(k2,k1)=SigmaP_n(k1,k2);
end
end % k2
end %k1
detSCV(n)=det([Sigma_n SigmaP_n; SigmaP_n' conj(Sigma_n)]);
else
detSCV(n)=det(Sigma_n);
end
end
% Third, sort and apply
[~,isort]=sort(detSCV);
Sigma_N=Sigma_N(:,:,isort);
for k=1:K
W(:,:,k)=W(isort,:,k);
end
%% Cast output
if iscell(X)
Wmat=W;
W=cell(K,1);
for k=1:K
W{k}=Wmat(:,:,k);
end
end
%% Return
return;
% END OF IVA_MG_OPTS
function test_iva_second_order
%% built-in test function for iva_second_order
N = 10; % number of sources
K = 10; % number of groups
T = 1000; % sample size
% generate the mixtures
S = zeros(N,T,K);
for n = 1 : N
temp1 = randn(K,T);
temp = zeros(K,T);
B = randn(K,K,3);
for p = 0 : 2
for t = 3 : T
temp(:,t) = temp(:,t) + B(:,:,p+1)*temp1(:,t-p); % introduce nonwhiteness and spatial correlation
end
end
for k = 1 : K
S(n,:,k) = temp(k,:);
S(n,:,k) = S(n,:,k) - mean(S(n,:,k));
S(n,:,k) = S(n,:,k)/sqrt(var(S(n,:,k)));
end
end
A = randn(N,N,K);
x = zeros(N,T,K);
for k = 1 : K
x(:,:,k) = A(:,:,k)*S(:,:,k);
end
% separation
figure;
W=iva_second_order(x,'jdiag_initW',false,'opt_approach','newton');
% show results
T1 = zeros(N,N);
for k = 1 : K
Tk = W(:,:,k)*A(:,:,k);
Tk = abs(Tk);
for n = 1 : N
Tk(n,:) = Tk(n,:)/max(abs(Tk(n,:)));
end
T1 = T1 + Tk/K;
end
P=zeros(N);
[~,imax]=max(T1);
ind=sub2ind([N N],1:N,imax);
P(ind)=1;
T1=P*T1;
imagesc(1:N,1:N,T1)
caxis([0 1])
axis xy
colormap('bone')
title('joint global matrix')
colorbar
disp('Ideally image is identity matrix.')
%% Available options:
% 'opt_approach','newton', ... % optimization type: gradient, (newton), quasi
% 'verbose',false, ... % verbose true enables print statements
% 'A',[], ... % true mixing matrices A, automatically sets verbose
% 'W_init',[], ... % initial estimates for demixing matrices in W
% 'jdiag_initW',true, ... % use CCA (K=2) or joint diagonalization (K>2)
% 'maxIter',512, ... % max number of iterations
% 'WDiffStop',1e-6, ... % stopping criterion
% 'alpha0',1.0 ... % initial step size scaling
% %% Example calls to iva_second_order with various options
% % note that the inputs could be made into a cell array with K entries
% W=iva_second_order(X,'jdiag_initW',false,'opt_approach','newton');
% [~,isi]=bss_isi(W,A,S);
% disp(['Newton IVA-G ISI: ' num2str(isi)])
W=iva_second_order(x,'A',A,'jdiag_initW',false,'opt_approach','gradient','whiten',true);
[~,isi]=bss_isi(W,A,S);
% disp(['Block-Newton IVA-G ISI: ' num2str(isi)])
% X_cell=cell(K,1);
% for k=1:K
% X_cell{k}=X(:,:,k);
% end
% W_cell=iva_second_order(X_cell,'jdiag_initW',false,'opt_approach','newton');
% for k=1:K
% W(:,:,k)=W_cell{k};
% end
% [~,isi]=bss_isi(W,A,S);
% disp(['Block-Newton IVA-G ISI: ' num2str(isi)])
%
% %% Generate test samples:
% S=complex(zeros(N,T,K)); % X(:,:,k)=A(:,:,k)*S(:,:,k);
%
% for n=1:N
% Z = zeros(K,T);
% B=randn(K);
% B=B*B';
%
% [V,D]=eig(B);
% C=V*sqrt(D);
% absrho=sqrt(rand(1,K));
% angrho=rand(1,K)*2*pi;
% rho=absrho.*exp(1j*angrho);
% for k=1:K
% Cggd=[1 rho(k); conj(rho(k)) 1];
% [X]=randggd_complex(T,Cggd,1);
% Z(k,:)=X(1,:);
% end
% Z=C*Z;
% % if n==1
% % for k=2:K
% % Z(k,:)=Z(1,:);
% % end
% % end
% S(n,:,:)=Z.';
% end
% A=randn(N,N,K)+1j*randn(N,N,K);
% X=S;
% for k=1:K
% X(:,:,k)=A(:,:,k)*S(:,:,k);
% end
%
%
% %% Available options:
% % 'opt_approach','newton', ... % optimization type: gradient, (newton), quasi
% % 'verbose',false, ... % verbose true enables print statements
% % 'A',[], ... % true mixing matrices A, automatically sets verbose
% % 'W_init',[], ... % initial estimates for demixing matrices in W
% % 'jdiag_initW',true, ... % use CCA (K=2) or joint diagonalization (K>2)
% % 'maxIter',512, ... % max number of iterations
% % 'WDiffStop',1e-6, ... % stopping criterion
% % 'alpha0',1.0 ... % initial step size scaling
%
% %% Example calls to iva_second_order with various options
% % note that the inputs could be made into a cell array with K entries
% W=iva_second_order(X,'A',A,'jdiag_initW',false,'opt_approach','newton','circular',true);
% [~,isi]=bss_isi(W,A,S);
% disp(['Circular IVA-G ISI: ' num2str(isi)])
% W=iva_second_order(X,'A',A,'jdiag_initW',false,'opt_approach','newton');
% [~,isi]=bss_isi(W,A,S);
% disp(['Non-Circ IVA-G ISI: ' num2str(isi)])
%%
return
function properties = getopt(properties,varargin)
%GETOPT - Process paired optional arguments as 'prop1',val1,'prop2',val2,...
%
% getopt(properties,varargin) returns a modified properties structure,
% given an initial properties structure, and a list of paired arguments.
% Each argumnet pair should be of the form property_name,val where
% property_name is the name of one of the field in properties, and val is
% the value to be assigned to that structure field.
%
% No validation of the values is performed.
%%
% EXAMPLE:
% properties = struct('zoom',1.0,'aspect',1.0,'gamma',1.0,'file',[],'bg',[]);
% properties = getopt(properties,'aspect',0.76,'file','mydata.dat')
% would return:
% properties =
% zoom: 1
% aspect: 0.7600
% gamma: 1
% file: 'mydata.dat'
% bg: []
%
% Typical usage in a function:
% properties = getopt(properties,varargin{:})
% Function from
% http://mathforum.org/epigone/comp.soft-sys.matlab/sloasmirsmon/[email protected]
% dgleich
% 2003-11-19
% Added ability to pass a cell array of properties
if ~isempty(varargin) && (iscell(varargin{1}))
varargin = varargin{1};
end;
% Process the properties (optional input arguments)
prop_names = fieldnames(properties);
TargetField = [];
for ii=1:length(varargin)
arg = varargin{ii};
if isempty(TargetField)
if ~ischar(arg)
error('Property names must be character strings');
end
%f = find(strcmp(prop_names, arg));
if isempty(find(strcmp(prop_names, arg),1)) %length(f) == 0
error('%s ',['invalid property ''',arg,'''; must be one of:'],prop_names{:});
end
TargetField = arg;
else
properties.(TargetField) = arg;
TargetField = '';
end
end
if ~isempty(TargetField)
error('Property names and values must be specified in pairs.');
end
function mag=vecmag(vec,varargin)
% mag=vecmag(vec)
% or
% mag=vecmag(v1,v2,...,vN)
%
% Computes the vector 2-norm or magnitude of vector. vec has size n by m
% represents m vectors of length n (i.e. m column-vectors). Routine avoids
% potential mis-use of norm built-in function. Routine is faster than
% calling sqrt(dot(vec,vec)) -- but equivalent.
if nargin==1
mag=sqrt(sum(vec.*conj(vec)));
else
mag=vec.*conj(vec);
for ii=1:length(varargin)
mag=mag+varargin{ii}.*conj(varargin{ii});
end
mag=sqrt(mag);
end
return
function [uvec,mag]=vecnorm(vec)
% [vec,mag]=vecnorm(vec)
% Returns the vector normalized by 2-norm or magnitude of vector.
% vec has size n by m represents m vectors of length n (i.e. m
% column-vectors).
[n,m]=size(vec);
if n==1
disp('vecnorm operates on column vectors, input appears to have dimension of 1')
end
uvec=zeros(n,m);
mag=vecmag(vec); % returns a 1 x m row vector
for ii=1:size(vec,1)
uvec(ii,:)=vec(ii,:)./mag;
end
% Equivalent to: uvec=vec./repmat(mag,size(vec,1),1);
% Which implementation is optimal depends on optimality criterion (memory
% vs. speed), this version uses the former criterion.
return
function [h,invQ,R]=decouple_trick(W,n,invQ,R)
% h=decouple_trick(W,n)
% h=decouple_trick(W,n,1)
% [h,invQ]=decouple_trick(W,n,invQ)
% [h,Q,R]=decouple_trick(W,n,Q,R)
%
% Computes the h vector for the decoupling trick [1] of the nth row of W. W
% can be K 'stacked' square matrices, i.e., W has dimensions N x N x K.
% The output vector h will be formatted as an N x K matrix. There are many
% possible methods for computing h. This routine provides four different
% (but of course related) methods depending on the arguments used.
%
% Method 1:
% h=decouple_trick(W,n)
% h=decouple_trick(W,n,0)
% -Both calls above will result in the same algorithm, namely the QR
% algorithm is used to compute h.
%
% Method 2:
% h=decouple_trick(W,n,~), where ~ is anything
% -Calls the projection method.
%
% Method 3:
% [h,invQ]=decouple_trick(W,n,invQ)
% -If two output arguments are specified then the recursive algorithm
% described in [2]. It is assumed that the decoupling will be performed in
% sequence see the demo subfunction for details.
% An example call sequence:
% [h1,invQ]=decouple_trick(W,1);
% [h2,invQ]=decouple_trick(W,2,invQ);
%
% Method 4:
% [h,Q,R]=decouple_trick(W,n,Q,R)
% -If three output arguments are specified then a recursive QR algorithm is
% used to compute h.
% An example call sequence:
% [h1,Q,R]=decouple_trick(W,1);
% [h2,Q,R]=decouple_trick(W,2,Q,R);
%
% See the subfunction demo_decoupling_trick for more examples. The demo
% can be executed by calling decouple_trick with no arguments, provides a
% way to compare the speed and determine the accuracy of all four
% approaches.
%
% Note that methods 2 & 3 do not normalize h to be a unit vector. For
% optimization this is usually not of interest. If it is then set the
% variable boolNormalize to true.
%
% Main References:
% [1] X.-L. Li & X.-D. Zhang, "Nonorthogonal Joint Diagonalization Free of Degenerate Solution," IEEE Trans. Signal Process., 2007, 55, 1803-1814
% [2] X.-L. Li & T. Adali, "Independent component analysis by entropy bound minimization," IEEE Trans. Signal Process., 2010, 58, 5151-5164
%
% Coded by Matthew Anderson (matt dot anderson at umbc dot edu)
% Version 01 - 20120919 - Initial publication
if nargin==0
help decouple_trick
demo_decouple_trick
return
end
if nargin==1
help decouple_trick
error('Not enough inputs -- see displayed help above.')
end
[M,N,K]=size(W);
if M~=N
error('Assuming W is square matrix.')
end
h=zeros(N,K);
% enables an additional computation that is usually not necessary if the
% derivative is of interest, it is only necessary so that sqrt(det(W*W'))
% = sqrt(det(Wtilde*Wtilde'))*abs(w'*h) holds. Furthermore, it is only
% necessary when using the recursive or projection methods.
%
% a user might wish to enable the calculation by setting the quantity below
% to true
boolNormalize=false;
if nargout==3
% use QR recursive method
% [h,Qnew,Rnew]=decouple_trick(W,n,Qold,Rold)
if n==1
invQ=zeros(N,N,K);
R=zeros(N,N-1,K);
end
for k=1:K
if n==1
Wtilde=W(2:N,:,k);
[invQ(:,:,k),R(:,:,k)]=qr(Wtilde');
else
n_last=n-1;
e_last = zeros(N-1,1);
e_last(n_last) = 1;
[invQ(:,:,k),R(:,:,k)]=qrupdate(invQ(:,:,k),R(:,:,k),-W(n,:,k)',e_last);
[invQ(:,:,k),R(:,:,k)]=qrupdate(invQ(:,:,k),R(:,:,k),W(n_last,:,k)',e_last);
end
h(:,k)=invQ(:,end,k); % h should be orthogonal to W(nout,:,k)'
end
elseif nargout==2
% use recursive method
% [h,invQ]=decouple_trick(W,n,invQ), for any value of n=1, ..., N
% [h,invQ]=decouple_trick(W,1), when n=1
if n==1
invQ=zeros(N-1,N-1,K);
end
% Implement a faster approach to calculating h.
for k=1:K
if n==1
Wtilde=W(2:N,:,k);
invQ(:,:,k)=inv(Wtilde*Wtilde');
else
if nargin<3
help decouple_trick
error('Need to supply invQ for recursive approach.')
end
[Mq,Nq,Kq]=size(invQ);
if Mq~=(N-1) || Nq~=(N-1) || Kq~=K
help decouple_trick
error('Input invQ does not have the expected dimensions.')
end
n_last=n-1;
Wtilde_last=W([(1:n_last-1) (n_last+1:N)],:,k);
w_last=W(n_last,:,k)';
w_current=W(n,:,k)';
c = Wtilde_last*(w_last - w_current);
c(n_last) = 0.5*( w_last'*w_last - w_current'*w_current );
%e_last = zeros(N-1,1);
%e_last(n_last) = 1;
temp1 = invQ(:,:,k)*c;
temp2 = invQ(:,n_last,k);
inv_Q_plus = invQ(:,:,k) - temp1*temp2'/(1+temp1(n_last));
temp1 = inv_Q_plus'*c;
temp2 = inv_Q_plus(:,n_last);
invQ(:,:,k) = inv_Q_plus - temp2*temp1'/(1+c'*temp2);