-
Notifications
You must be signed in to change notification settings - Fork 0
/
gaussAdapt.m
1438 lines (1144 loc) · 38.8 KB
/
gaussAdapt.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 [xmin,fmin,counteval,out] = gaussAdapt(fitfun,xstart,inopts)
global amp;
% Hacking for non-linear SDP solver
global C;
global counteval;
%-------------------------------------------------------------------------
% Implementation of the Gaussian Adaptation algorithm for design centering
% Black-box optimization and adaptive MCMC sampling
%
% Input:
% fitfun: Name of the fitness/target function as string or function handle
% xstart: initial candidate solution/sample
% inopts: option structure that determines internal strategy parameters (see code for details)
%
% Output:
% xmin: minimum candidate solution found by GaA (when using GaA as optimizer)
% fmin: fitness value of the xmin (when using GaA as optimizer)
% counteval: Number of function evaluations
% out: Output structure storing all relevant information (see code for
% details)
%
% When using this code please cite:
%
% C. L. Mueller and I. F. Sbalzarini. Gaussian Adaptation revisited - an
% entropic view on Covariance Matrix Adaptation.
% In Proc. EvoStar, volume 6024 of Lecture Notes in Computer Science,
% pages 432?441, Istanbul, Turkey, April 2010. Springer.
%
% C. L. Mueller and I. F. Sbalzarini. Gaussian Adaptation as a unifying
% framework for continuous black-box optimization and adaptive Monte Carlo sampling.
% In Proc. IEEE Congress on Evolutionary Computation (CEC), Barcelona,
% Spain, July 2010.
%
% Christian L. Mueller
% MOSAIC group, ETH Zurich, Switzerland
%
% Version 01/11
%
%-------------------------------------------------------------------------
% dimension of the problem
N = length(xstart);
% Options defaults: Stopping criteria % (value of stop flag)
defopts.StopFitness = -Inf; % stop if f(xmin) < stopfitness, minimization';
defopts.MaxIter = 1e4*(N); % maximal number of iterations/function evaluations';
defopts.TolX = 1e-12; % restart if history of xvals smaller TolX';
defopts.TolFun = 1e-9; % restart if history of funvals smaller TolFun';
defopts.TolR = 1e-9; % restart if step size smaller TolR';
defopts.TolCon = 1e-9; % restart if threshold and fitness converge';
defopts.BoundActive = 0; % Flag for existence of bounds
defopts.BoundPenalty = 0; % Flag for use of penalty term outside bounds;
defopts.LBounds = -Inf; % lower bounds, scalar or Nx1-vector';
defopts.UBounds = Inf; % upper bounds, scalar or Nx1-vector';
defopts.A = []; % Constraint matrix Ax<=b;
defopts.E = []; % Constraint ellipsoid (x-cE)'*E*(x-cE) <=1;
defopts.cE = []; % Constraint ellispoid center (x-cE)'E(x-cE) <=1;
defopts.bVec = []; % constraint vector Ax<=b;
defopts.bRestart = 1; % Flag for restart activation;
defopts.ThreshRank = 0; % Flag for threshold based on ranks (Experimental)
defopts.PopMode = 0; % Flag for population mode (ToDo);
defopts.Display = 'off'; % Display 2D landscape while running';
defopts.Plotting = 'on'; % Plot progress while running';
defopts.VerboseModulo = 1e3; % >=0, command line messages after every i-th iteration';
defopts.SavingModulo = 1e2; % >=0, saving after every i-th iteration';
defopts.bSaving = 'on'; % [on|off] save data to file';
defopts.bSaveCov = 0; % save covariance matrices' ('1' results in huge files);
defopts.funArgs = []; % give additional target function arguments
%(scalar, vectors or matrix) if necessary
% Default options for algorithmic parameters
defopts.valP = 1/exp(1); % 0.37... Hitting probability
defopts.r = 1; % Step size of the initial covariance
defopts.initQ = eye(N,N); % Initial Cholesky matrix
defopts.MaxR = Inf; % maximal allowed step size
defopts.MinR = 0; % minimal allowed step size
defopts.MaxCond = 1e20*N; % maximal allowed condition
defopts.N_mu = exp(1)*N; % Mean adaptation weight
defopts.N_C = (N+1)^2/log(N+1); % Matrix adaptation weight
defopts.N_T = exp(1)*N; % Constraint adaptation weight
defopts.inc_T = 2; % Factor for N_T increase at restart (optimization)
defopts.beta = 1/defopts.N_C; % Step size increase/decrease factor
defopts.ss = 1 + defopts.beta*(1-defopts.valP); % Expansion upon success
defopts.sf = 1 - defopts.beta*(defopts.valP); % Contraction otherwise
% Option for optimization/design-centering/MCMC sampling mode
% mode = 0 design centering
% mode = 1 optimization
% mode = 2 MCMC sampling
defopts.mode = 1;
% Option for initial threshold
% In the design centering mode c_T is constant. Values smaller than this value are
% considered as feasible points
% In the optimization mode this value is adapted
% In the MCMC mode this threshold is neglected
defopts.c_T = Inf;
% Option for initial sample point matrix
defopts.initX = [];
% ---------------------- Handling Input Parameters ----------------------
if isempty(fitfun)
error('Objective function not determined');
end
if ~ischar(fitfun)
error('first argument FUN must be a string');
end
if nargin < 2
xstart = [];
end
if isempty(xstart)
error('Initial search point, and problem dimension, not determined');
end
% Merge options inopts and defopts
if nargin < 3 || isempty(inopts) % no input options available
inopts = [];
opts = defopts;
else
opts = getoptions(inopts, defopts);
end
% ---------------------- Setup algorithmic Parameters ----------------------
% Options for algorithmic parameters
P = opts.valP;
if ~isfield(inopts,'N_T') && isfield(inopts,'N_C')
opts.N_T = opts.N_C/2;
end
if ~isfield(inopts,'beta') && isfield(inopts,'N_C')
opts.beta = 1/(opts.N_C);
end
if ~isfield(inopts,'ss')
opts.ss = 1 + opts.beta*(1-opts.valP); % Expansion
end
if ~isfield(inopts,'sf')
opts.sf = 1 - opts.beta*(opts.valP); % Contraction
end
if isfield(inopts,'UBounds') && isfield(inopts,'LBounds')
opts.BoundActive = 1;
if ~isfield(inopts,'MaxR')
opts.MaxR = 0.5*max(opts.UBounds-opts.LBounds);
end
% Make vector out of scalar input
if size(opts.UBounds,1)==1
opts.UBounds = ones(N,1)*opts.UBounds;
end
if size(opts.LBounds,1)==1
opts.LBounds = ones(N,1)*opts.LBounds;
end
end
% Algorithmic parameters
N_mu = opts.N_mu;
N_C = opts.N_C;
N_T = opts.N_T;
beta = opts.beta;
ss = opts.ss;
sf = opts.sf;
r = opts.r;
r_init = r;
rMax = opts.MaxR;
rMin = opts.MinR;
inc_T = opts.inc_T;
condMax = opts.MaxCond;
bAdapt=0;
P_emp = 0;
% Display the current options
% opts
% pause
% Initialize dynamic (internal) strategy parameters
Q = opts.initQ;
C = r^2*Q'*Q;
[eigVecs,eigVals] = eig(Q*Q');
C_old = C;
% Condition of initial Q
condC = cond(Q*Q');
% Initialize plotting figure
if strcmp(opts.Plotting,'on')
figure(42)
hold on
grid on
lastInd = 1;
lastSave = 1;
lastEigVals = ones(N,1);
end
% Compute function for 2D plotting
if strcmp(opts.Display,'on')
if strcmp(fitfun,'benchmark_func')
global initial_flag;
initial_flag=0;
end
figure(23)
try
x = linspace(opts.LBounds(1),opts.UBounds(1),100);
y = linspace(opts.LBounds(2),opts.UBounds(2),100);
f = zeros(length(x),length(y));
catch
error('Displaying a function requires boundary setting')
end
i=1;
j=1;
for j=1:length(x)
for i=1:length(y)
if isempty(opts.funArgs)
f(i,j)=feval(fitfun, [x(j);y(i)]);
else
f(i,j)=feval(fitfun, [x(j);y(i)],opts.funArgs);
end
end
end
[X,Y]=meshgrid(x,y);
% meshc(Y,X,f)
% hold on
if opts.mode ~= 0
if strcmp(fitfun,'fnoisysphere')
contour(X,Y,f,10)
else
contour(X,Y,f,100)
end
if strcmp(fitfun,'benchmark_func')
initial_flag=0;
end
else
% Special display for design centering
surf(X,Y,f)
colormap('autumn')
shading flat
view(0,90)
xlim([opts.LBounds(1) opts.UBounds(1)])
ylim([opts.LBounds(2) opts.UBounds(2)])
end
hold on
end
% ----------------- Setup initial settings ---------------------------
% Determine start fitness value and threshold
if isempty(opts.funArgs)
c_T=feval(fitfun, xstart);
else
c_T=feval(fitfun, xstart,opts.funArgs);
end
arfitness=c_T;
% Design centering or optimization
if (opts.mode==0)
if isfield(inopts,'c_T')
c_T = opts.c_T;
% Samples below threshold are considered feasible points
threshold = c_T;
end
end
% For testing issues and (possible) restarts save the initial values
arfitness_init = arfitness;
c_T_init = c_T;
N_mu_init = N_mu;
N_C_init = N_C;
N_T_init = N_T;
lastxAcc = xstart;
lastfAcc = arfitness_init;
lBnd=0;
% Linear constraints active
if ~(isempty(opts.A) && isempty(opts.bVec))
lBnd=1;
A = inopts.A;
b = inopts.bVec;
copts.thinInterval=1;
copts.burnin=2*N;
copts.bndEps = 1e-15;
end
eBnd=0;
if ~(isempty(opts.E) && isempty(opts.cE))
eBnd=1;
E = inopts.E;
cE = inopts.cE;
copts.thinInterval=1;
copts.burnin=2*N;
copts.bndEps = 1e-15;
end
% Transform lower/uppper bounds into matrix inequalities
bBnd = 0;
if opts.BoundActive && ~opts.BoundPenalty
bBnd=1;
if isfield(inopts,'UBounds') && isfield(inopts,'LBounds')
A = [-eye(N,N);eye(N,N)];
b = [-opts.LBounds;opts.UBounds];
end
if isfield(inopts,'UBounds') && ~isfield(inopts,'LBounds')
A = eye(N,N);
b = opts.UBounds;
end
if ~isfield(inopts,'UBounds') && isfield(inopts,'LBounds')
A = -eye(N,N);
b = -opts.LBounds;
end
copts.thinInterval=1;
copts.burnin=2*N;
copts.bndEps = 1e-12;
end
% Number of iterations
counteval = 1;
% Number of accepted points
numAcc = 0;
% Number of accepted points within a restart
rNumAcc = 0;
% ----------------- Setup output Parameters ---------------------------
mu = xstart;
mu_old = mu;
arx = xstart;
% Restart specific bestever
currxBest = xstart;
currfBest = arfitness;
% Overall bestever
xmin = xstart;
fmin = arfitness;
Qmin = Q;
rmin = r;
% History for rank-based selection (experimental)
histLen=10*N;%2*ceil(4+3*log(N));
histFAcc = zeros(histLen,1);
histXAcc = zeros(histLen,N);
histFAcc(:) = currfBest;
sortedHist = histFAcc;
if strcmp(opts.bSaving,'on')
% Trace of raw samples and function values
xRaw=zeros(opts.MaxIter/opts.SavingModulo,N);
xRaw(1,:)=xstart;
fRaw=zeros(opts.MaxIter/opts.SavingModulo,1);
fRaw(1) = c_T;
% Trace of accepted samples and function values
xAcc=zeros(opts.MaxIter/opts.SavingModulo,N);
xAcc(1,:)=xstart';
fAcc=zeros(opts.MaxIter/opts.SavingModulo,1);
fAcc(1) = arfitness;
cntAcc=zeros(opts.MaxIter/opts.SavingModulo,1);
% Trace of best samples and function values
xBest=zeros(opts.MaxIter/opts.SavingModulo,N);
xBest(1,:)=xstart;
fBest=zeros(opts.MaxIter/opts.SavingModulo,1);
fBest(1) = c_T;
% Vector of step lengths
rVec=zeros(opts.MaxIter/opts.SavingModulo,1);
rVec(1)=r;
% Vector of KL divergence
KLVec=zeros(opts.MaxIter/opts.SavingModulo,1);
KLVec(1)=0;
KL=0;
% Vector of mu
muVec = zeros(opts.MaxIter/opts.SavingModulo,N);
muVec(1,:)=mu;
% Vector of acceptance thresholds
c_TVec=zeros(opts.MaxIter/opts.SavingModulo,1);
c_TVec(1)=c_T;
% Vector of empirical acceptance probability
P_empVec = zeros(opts.MaxIter/opts.SavingModulo,1);
P_empVec(1)=opts.valP;
% Cell array of Q matrices
if opts.bSaveCov==1
QCell = cell(opts.MaxIter/opts.SavingModulo,1);
QCell{1} = Q;
end
% Vector of evaluation indices
countVec = zeros(opts.MaxIter/opts.SavingModulo,1);
countVec(1) = 1;
% Cell array with stop flags
stopFlagCell = cell(1,1);
end
% Final initialization
saveInd = 2;
stopFlag='';
cntInitX = 1;
% -------------------- Generation Loop --------------------------------
% Reserve the last evaluation for the fitness at the last mu
while counteval < (opts.MaxIter-1)
arfitness_old=arfitness;
C_old = C;
counteval = counteval+1;
if strcmp(opts.Display,'on') && (mod(counteval,opts.VerboseModulo)==0)
figure(23)
error_ellipse(C([1,N],[1,N]),mu([1,N],1),'style','k')
grid on
end
% Handle boundaries
penalty=0;
if lBnd || bBnd
arx_old = arx;
%arx = mvntruncHR(mu,r,C./r^2,A,b,1);
%arx = mvntruncLMI(mu,r,C./r^2,A,1);
%arx = mvntrunc(mu,r,C./r^2,A,b,1,copts);
arx = mvntruncFortran(mu,r,C./r^2,A,b,1,copts.burnin,copts.thinInterval);
%arx = mvntruncFortran(mu,r,eigVecs,diag(eigVals),A,b,1,copts.burnin,copts.thinInterval);
arz = Q'\((arx-mu)./r);
elseif eBnd
arx_old = arx;
arx = mvntruncElli(mu,r,C,cE,E,1,copts);
arz = Q'\((arx-mu)./r);
% elseif bBnd
%
% arx_old = arx;
% arx = mvntrunc2(mu,C,[opts.LBounds,opts.UBounds],1,copts);
% arz = Q'\((arx-mu)./r);
else
% Generate a N(0,1) variable
arz = randn(N,1); % array of standard normally distributed mutation vectors
% Sample from N(mu,C) distribution
arx_old = arx;
arx = mu + r * (Q * arz);
% Box constraints active
if opts.BoundActive
arxNoBound=arx;
arx=max([arx,opts.LBounds],[],2);
arx=min([arx,opts.UBounds],[],2);
if opts.BoundPenalty
% Simple boundary handling
penFac=mean(abs(sortedHist(1:N)));
penalty=penFac*norm(arx-arxNoBound).^2;
end
end
end
% Plug-in local optimizer (experimental)
% arx=fminunc(fitfun,arx);
% Objective/target function call
if isempty(opts.funArgs)
arfitness=feval(fitfun, arx)+penalty;
% Just for recording
% muFitness=feval(fitfun, mu);
else
arfitness=feval(fitfun, arx,opts.funArgs)+penalty;
% Just for recording
% muFitness=feval(fitfun, mu,opts.funArgs);
end
% Save best sample and fitness values per restart
if arfitness<currfBest
currfBest = arfitness;
currxBest = arx';
end
% Save best ever sample and fitness values across restarts
if arfitness<fmin
fmin = arfitness;
xmin = arx;
Qmin = Q;
rmin = r;
end
if strcmp(opts.Plotting,'on') && ...
(mod(counteval,opts.VerboseModulo)==0) && strcmp(opts.bSaving,'on')
%tic
% shift values such that the minimal value is 0
if (opts.StopFitness > -Inf)
biasVal = -opts.StopFitness;
else
biasVal = 0;
end
currInd = counteval-1;
currIndices = lastInd:opts.SavingModulo:currInd;
currSaves = lastSave:saveInd-1;
%[eigVecs,eigVals] = eig(C./r^2); % eigen decomposition for plotting
eigValsD=diag(eigVals);
try
figure(42)
subplot(2,2,1)
plot([currIndices],muVec(currSaves,:)')
title(['Current best: ',num2str(currfBest)])
grid on
hold on
subplot(2,2,2)
semilogy([currIndices],rVec(currSaves,:)')
title(['Current step size: ',num2str(r),' and KL divergence: ',num2str(KL)])
grid on
hold on
semilogy([currIndices],KLVec(currSaves,:)','r')
subplot(2,2,3)
semilogy([currIndices],biasVal+fBest([currSaves]))
hold on
grid on
semilogy([currIndices],biasVal+c_TVec(currSaves,:)','r')
title(['Current threshold: ',num2str(c_T)])
% subplot(2,2,4)
% plot([currIndices],P_empVec([currSaves]))
% grid on
% hold on
% title(['Current acceptance prob: ',num2str(P_emp)])
subplot(2,2,4)
if N==2
semilogy([lastInd,currInd],[1./sort(lastEigVals),1./sort(eigValsD)]','-')
else
semilogy([lastInd,currInd],[1./sort(lastEigVals),1./sort(eigValsD)],'-')
end
grid on
hold on
title(['Condition of C: ',num2str(max(eigValsD)/min(eigValsD))])
end
lastEigVals = eigValsD;
lastInd = currInd;
lastSave = saveInd-1;
drawnow;
%toc
end
% Design centering
if (opts.mode==0)
threshold = c_T;
% Check whether to adapt or not
bAdapt = (arfitness<threshold);
% Optimization
elseif (opts.mode==1)
% Check whether fitness/rank-based selection is used
if opts.ThreshRank % (experimental)
threshold = sortedHist(floor(opts.valP*histLen));
else
threshold = c_T;
end
% Check whether to adapt or not
bAdapt = (arfitness<threshold);
% MCMC Sampling
elseif (opts.mode==2)
% Metropolis criterion for adaptive MCMC (M-GaA)
accProb = min(1,arfitness/arfitness_old);
% accProb = min(1,exp(arfitness_old-arfitness));
bAdapt = (rand<accProb);
end
% Adapt moments upon acceptance (for all modes of operation)
if bAdapt
% Count accepted solutions
numAcc = numAcc + 1;
rNumAcc = rNumAcc + 1;
% Expand r by factor ss
r = r*ss;
% Upper bound for step size to avoid numerical errors
r = max(min(r,rMax),rMin);
%%%%%%%%%%%%%%%%%%%%%%
% Adapt threshold c_T when optimizing
%%%%%%%%%%%%%%%%%%%%%%
if (opts.mode==1)
% Update history of accepted f and x
histFAcc(2:end)=histFAcc(1:end-1);
histFAcc(1)=arfitness;
sortedHist = sort(histFAcc,'ascend');
histXAcc(2:end,:)=histXAcc(1:end-1,:);
histXAcc(1,:)=arx';
if opts.ThreshRank %(experimental)
% threshold for last accepted sample
c_T = threshold;
else
% Standard fitness-dependent threshold decrease
c_T = (1-1/N_T)*c_T + arfitness/N_T;
% Linear threshold decrease (experimental)
% c_T = (1-counteval/opts.MaxIter)*300;
end
end
%%%%%%%%%%%%%%%%%%%%%%
% Adapt mu
%%%%%%%%%%%%%%%%%%%%%%
gamma = 1;%counteval;
mu_old=mu;
mu = (1-1/(gamma*N_mu))*mu + arx/(gamma*N_mu);
%%%%%%%%%%%%%%%%%%%%%%
% Adapt covariance
%%%%%%%%%%%%%%%%%%%%%%
% This would be a direct update of C
% C_direct = (1-1/N_C)*C + ((mu-arx)*(mu-arx)')/N_C
% In order to avoid numerical errors
if (condC<condMax) && (condC > 0)
deltaC = (1-1/N_C)*eye(N,N) + arz*arz'./N_C;
% set deltaC to identity if covariance adaptation is not
% required (experimental)
% deltaC = eye(N,N);
% Adapt Q
deltaC = triu(deltaC)+triu(deltaC,1)'; % enforce symmetry
[B,eigValsD] = eig(deltaC); % eigen decomposition, B==normalized eigenvectors
deltaQ = B*diag(sqrt(diag(eigValsD)))*B'; % deltaQ contains standard deviations now
if any(imag(deltaQ(:)))
deltaQ
error('deltaQ is imaginary')
end
% Update Cholesky matrix
Q = Q*deltaQ;
if any(imag(Q(:)))
Q
error('Q is imaginary')
end
else
if (mod(counteval,opts.VerboseModulo)==0)
disp( '-------------------------------------------');
disp(' Condition of C is too large and regularized');
disp( '-------------------------------------------');
end
% Regularize Q
Q = Q + 1/N*eye(N,N);
end
% Normalize volume of Q to 1
detQ=det(Q);
Q = Q./((detQ).^(1/N));
% Update condition of C
[eigVecs,eigVals] = eig(Q*Q');
condC = max(diag(eigVals))/min(diag(eigVals));
if any(diag(eigVals)<0)
saveInd
xRaw(max(1,saveInd-10):saveInd,:)
eigVecs
eigVals
condC
detQ
Q*Q'
warning('C contains negative eigenvalues')
eigVals(eigVals<0)=1e-3;
Q = eigVecs'*eigVals*eigVecs;
end
% New full covariance matrix
C = r^2*Q*Q';
% GaA with vanishing adaptation (experimental)
% N_C = counteval * N_C_init;
lastxAcc = arx;
lastfAcc = arfitness;
else
% Contract r by factor sf
r=r*sf;
% New full covariance matrix
C = sf^2*C;
% When MCMC sampling is on
% set new position and fitness to old one (Metropolis criterion)
if (opts.mode == 2)
arfitness = arfitness_old;
arx = arx_old;
end
end
% Save accepted points (either really accepted or old one) TODO
if strcmp(opts.bSaving,'on') && (mod(counteval,opts.SavingModulo)==0)
cntAcc(saveInd,1)=counteval;
xAcc(saveInd,:)=lastxAcc';
fAcc(saveInd,1)=lastfAcc;
end
% Restart and stop flag checks in optimization mode
if (opts.mode == 1)
% Break, if fitness is good enough
if arfitness <= opts.StopFitness
fmin=arfitness;
xmin=arx;
stopFlag='fitness';
break;
end
% Restart when history of accepted samples is converging
%%%%% TolFun %%%%%
currTolFun = abs(max(histFAcc)-min(histFAcc));
if (currTolFun<opts.TolFun) && rNumAcc>histLen
stopFlag='TolFun';
end
%%%%% TolX %%%%%
currTolX = norm(histXAcc(1,:)-histXAcc(end,:));
if (currTolX<opts.TolX)&& rNumAcc>histLen
stopFlag='TolX';
end
%%%%% TolR %%%%%
if (r<opts.TolR)
stopFlag='TolR';
end
%%%%% TolCon %%%%%
currTolCon = abs(c_T-currfBest);
if N_T~=1 && currTolCon<opts.TolCon && rNumAcc>histLen
stopFlag='TolCon';
end
% Restart when Restart flag is active AND stop flags are active
if opts.bRestart && ~(strcmp(stopFlag,''))
% Show reason for restart
disp([num2str(counteval),': Restart due to: ',stopFlag]);
% Record stop flags
if size(stopFlagCell,1)==1
stopFlagCell{1,1}=stopFlag;
else
stopFlagCell{end+1,1}=stopFlag;
end
% Reset stopFlag
stopFlag='';
% Reset Gaussian parameters
r = r_init;
Q = eye(N,N);
C = r^2*Q'*Q;
C_old = C;
% Create new start point and handle boundaries
if opts.BoundActive==1
if ~isempty(opts.initX);
cntInitX = max(1,mod(cntInitX,size(opts.initX,2)+1));
mu = opts.initX(:,cntInitX);
mu_old = mu;
arx = mu;
cntInitX = cntInitX+1;
disp('Use user-defined starting points')
elseif isfield(inopts,'UBounds') && isfield(inopts,'LBounds')
mu = opts.LBounds + rand(N,1).*(opts.UBounds-opts.LBounds);
arx = mu;
mu_old = mu;
else
mu = arx;
arx = mu;
mu_old = mu;
end
else
mu = xstart;
arx = xstart;
mu_old = mu;
end
% New start value
if isempty(opts.funArgs)
c_T=feval(fitfun, arx);
else
c_T=feval(fitfun, arx, opts.funArgs);
end
counteval = counteval+1;
arfitness = c_T;
rNumAcc = 0;
% Restart with larger N_T (see CEC 2010 paper)
N_T = inc_T*N_T;
% Reset history for rank-based selection/tolerance checks
histFAcc = arfitness*ones(histLen,1);
sortedHist = histFAcc;
currfBest=arfitness;
histXAcc = repmat(arx',histLen,1);
end
end
% Empirical acceptance probability
P_emp = numAcc/counteval;
% Save data
if strcmp(opts.bSaving,'on') && (mod(counteval,opts.SavingModulo)==0)
rVec(saveInd)=r;
muVec(saveInd,:)=mu;
c_TVec(saveInd)=c_T;
P_empVec(saveInd)=P_emp;
invC = inv(C);
KL = 1/2*(log(det(C))-log(det(C_old)) + trace(invC*C_old) + (mu-mu_old)'*invC*(mu-mu_old) - N);
KLVec(saveInd) = KL;
% Cell array of Q matrices if covariances are stored
if opts.bSaveCov==1
QCell{saveInd}=Q;
end
fRaw(saveInd)=arfitness;
xRaw(saveInd,:)=arx;
fBest(saveInd)=currfBest;
xBest(saveInd,:)=currxBest;
countVec(saveInd)=counteval;
saveInd = saveInd+1;
end
if (mod(counteval,opts.VerboseModulo)==0)
disp( '-------------------------------------------');
disp([' Number of iterations: ',num2str(counteval)]);
disp([' P_acc: ',num2str(P_emp)]);
disp([' Search radius: ',num2str(r)]);
if opts.mode == 1
disp([' Current fitness: ',num2str(arfitness)]);
disp([' Threshold: ',num2str(c_T)]);
disp([' TolCon: ',num2str(currTolCon)]);
disp([' TolX: ',num2str(currTolX)]);
end
end
% No restart but stop flag is set
if ~(strcmp(stopFlag,''))
break;
end
end % while, end generation loop
% Final sample is reserved for the final mu vector
if (counteval==(opts.MaxIter-1))
% Final objective function call is reserved for mu
if isempty(opts.funArgs)
muFitness=feval(fitfun, mu);
else
muFitness=feval(fitfun, mu,opts.funArgs);
end
if muFitness <= opts.StopFitness
currfBest = muFitness;
currxBest = mu;
stopFlag='fitness';
if muFitness <=fmin
fmin = muFitness;
xmin = mu;
Qmin = Q;
rmin=r;
end
else
stopFlag='MaxIter';
end
counteval = counteval+1;
end
if strcmp(opts.bSaving,'on')
% Save the last evaluation
rVec(saveInd) = r;
muVec(saveInd,:) = mu;
xRaw(saveInd,:) = arx;
fRaw(saveInd,:) = arfitness;
c_TVec(saveInd) = c_T;
P_empVec(saveInd) = P_emp;
KLVec(saveInd) = KL;
if opts.bSaveCov==1
QCell{saveInd}=Q;
end