-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmaesV255.m
2148 lines (1965 loc) · 77.9 KB
/
cmaesV255.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, ... % minimum search point of last iteration
fmin, ... % function value of xmin
counteval, ... % number of function evaluations done
stopflag, ... % stop criterion reached
out, ... % struct with various histories and solutions
bestever ... % struct containing overall best solution (for convenience)
] = cmaes( ...
fitfun, ... % name of objective/fitness function
xstart, ... % objective variables initial point, determines N
insigma, ... % initial coordinate wise standard deviation(s)
inopts, ... % options struct, see defopts below
varargin ) % arguments passed to objective function
% cmaes.m, Version 2.55, last change: July, 2007
% CMAES implements an Evolution Strategy with Covariance Matrix
% Adaptation (CMA-ES) for nonlinear function minimization. For
% introductory comments and copyright see end of file (type 'type
% cmaes'). It should run with MATLAB (Windows, Linux) and Octave
% (Linux, package octave-forge is needed).
%
% OPTS = CMAES returns default options.
% OPTS = CMAES('defaults') returns default options quietly.
% OPTS = CMAES('displayoptions') displays options.
% OPTS = CMAES('defaults', OPTS) supplements options OPTS with default
% options.
%
% XMIN = CMAES(FUN, X0, SIGMA[, OPTS]) locates the minimum XMIN of
% function FUN starting from column vector X0 with the initial
% coordinate wise search standard deviation SIGMA.
%
% Input arguments:
%
% FUN is a string function name like 'myfun'. FUN takes as argument a
% column vector of size of X0 and returns a scalar. An easy way to
% implement a hard non-linear constraint is to return NaN. Then,
% this function evaluation is not counted and a newly sampled
% point is tried immediately.
%
% X0 is a column vector, or a matrix, or a string. If X0 is a matrix,
% mean(X0, 2) is taken as initial point. If X0 is a string like
% '2*rand(10,1)-1', the string is evaluated first.
%
% SIGMA is a scalar, or a column vector of size(X0,1), or a string
% that can be evaluated into one of these. SIGMA determines the
% initial coordinate wise standard deviations for the search.
% Setting SIGMA one third of the initial search region is
% appropriate, e.g., the initial point in [0, 6]^10 and SIGMA=2
% means cmaes('myfun', 3*rand(10,1), 2). If SIGMA is missing and
% size(X0,2) > 1, SIGMA is set to sqrt(var(X0')'). That is, X0 is
% used as a sample for estimating initial mean and variance of the
% search distribution.
%
% OPTS (an optional argument) is a struct holding additional input
% options. Valid field names and a short documentation can be
% discovered by looking at the default options (type 'cmaes'
% without arguments, see above). Empty or missing fields in OPTS
% invoke the default value, i.e. OPTS needs not to have all valid
% field names. Capitalization does not matter and unambiguous
% abbreviations can be used for the field names. If a string is
% given where a numerical value is needed, the string is evaluated
% by eval, where 'N' expands to the problem dimension
% (==size(X0,1)) and 'popsize' to the population size.
%
% [XMIN, FMIN, COUNTEVAL, STOPFLAG, OUT, BESTEVER] = ...
% CMAES(FITFUN, X0, SIGMA)
% returns the best (minimal) point XMIN (found in the last
% generation); function value FMIN of XMIN; the number of needed
% function evaluations COUNTEVAL; a STOPFLAG value as cell array,
% where possible entries are 'fitness', 'tolx', 'tolupx', 'tolfun',
% 'maxfunevals', 'maxiter', 'stoptoresume', 'manual',
% 'warnconditioncov', 'warnnoeffectcoord', 'warnnoeffectaxis',
% 'warnequalfunvals', 'warnequalfunvalhist', 'bug' (use
% e.g. any(strcmp(STOPFLAG, 'tolx')) or findstr(strcat(STOPFLAG,
% 'tolx')) for further processing); a record struct OUT with various
% output, where the array HIST.MEAN.X contains the evolution of the
% mean value and the struct SOLUTIONS.BESTEVER contains the overall
% best evaluated point X with function value F evaluated at evaluation
% count EVALS. BESTEVER equals OUT.SOLUTIONS.BESTEVER.
%
% A regular manual stop can be achieved via the file signals.par. The
% program is terminated if the first two non-white sequences in any
% line of this file are 'stop' and the value of the SaveFileName
% option (by default 'variablescmaes.mat'). Also a run can be skipped.
% Given, for example, 'skip SaveFileName run 2', skips the second run
% (if option Restarts is at least 2) and another run will be started.
%
% To run the code completely quietly set Display, VerboseModulo, and
% Plotting options to 0. When OPTS.Saving==1 (default) everything is
% saved in file OPTS.SaveFileName (default 'variablescmaes.mat')
% permitting to investigate the recent result (e.g. plot with function
% plotcmaes) even while CMAES is still running (which can be quite
% useful on expensive objective functions) and to resume the search
% afterwards by using the resume option.
%
% To find the best ever evaluated point load the variables typing
% "es=load('variablescmaes')" and investigate the variable
% es.out.solutions.bestever. To further control data sampling behavior
% use SaveModulo option.
%
% The primary strategy parameter to play with is OPTS.PopSize, which
% can be increased from its default value. Increasing the population
% size (by default together with the parent number OPTS.ParentNumber)
% improves global search properties in exchange to speed. Speed
% decreases, as a rule, at most linearely with increasing population
% size. It is advisable to begin with the default small population
% size. The options Restarts and IncPopSize can be used for an
% automated multistart where the population size is increased by the
% factor IncPopSize (two by default) before each restart. X0 (given as
% string) is reevaluated for each restart. Stopping options
% StopFunEvals, StopIter, MaxFunEvals, and Fitness terminate the
% program, all others including MaxIter invoke another restart, where
% the iteration counter is reset to zero.
%
% Examples:
%
% XMIN = cmaes('myfun', 5*ones(10,1), 1.5); starts the search at
% 10D-point 5 and initially searches mainly between 5-3 and 5+3
% (+- two standard deviations), but this is not a strict bound.
% 'myfun' is a name of a function that returns a scalar from a 10D
% column vector.
%
% opts.LBounds = 0; opts.UBounds = 10;
% X=cmaes('myfun', 10*rand(10,1), 5, opts);
% search within lower bound of 0 and upper bound of 10. Bounds can
% also be given as column vectors. If the optimum is not located
% on the boundary, use rather a penalty approach to handle bounds.
%
% opts=cmaes; opts.StopFitness=1e-10;
% X=cmaes('myfun', rand(5,1), 0.5, opts); stops the search, if
% the function value is smaller than 1e-10.
%
% [X, F, E, STOP, OUT] = cmaes('myfun2', 'rand(5,1)', 1, [], P1, P2);
% passes two additional parameters to the function MYFUN2.
%
% See also FMINSEARCH, FMINUNC, FMINBND.
cmaVersion = '2.54';
% ----------- Set Defaults for Input Parameters and Options -------------
% These defaults may be edited for convenience
% Input Defaults (obsolete, these are obligatory now)
definput.fitfun = 'felli'; % frosen; fcigar; see end of file for more
definput.xstart = rand(10,1); % 0.50*ones(10,1);
definput.sigma = 0.3;
% Options defaults: Stopping criteria % (value of stop flag)
defopts.StopFitness = '-Inf % stop if f(xmin) < stopfitness, minimization';
defopts.MaxFunEvals = 'Inf % maximal number of fevals';
defopts.MaxIter = '1e3*(N+5)^2/sqrt(popsize) % maximal number of iterations';
defopts.StopFunEvals = 'Inf % stop after resp. evaluation to resume later';
defopts.StopIter = 'Inf % stop after resp. iteration to resume later';
defopts.TolX = '1e-11*max(insigma) % stop if x-change smaller TolX';
defopts.TolUpX = '1e3*max(insigma) % stop if x-changes larger TolUpX';
defopts.TolFun = '1e-12 % stop if fun-changes smaller TolFun';
defopts.TolHistFun = '1e-13 % stop if back fun-changes smaller TolHistFun';
defopts.StopOnWarnings = 'yes % ''no''==''off''==0, ''on''==''yes''==1 ';
% Options defaults: Other
defopts.DiffMaxChange = 'Inf % maximal variable change(s), can be Nx1-vector';
defopts.DiffMinChange = '0 % minimal variable change(s), can be Nx1-vector';
defopts.WarnOnEqualFunctionValues = ...
'yes % ''no''==''off''==0, ''on''==''yes''==1 ';
defopts.LBounds = '-Inf % lower bounds, scalar or Nx1-vector';
defopts.UBounds = 'Inf % upper bounds, scalar or Nx1-vector';
defopts.EvalParallel = 'no % objective function FUN accepts NxM matrix, with M>1?';
defopts.EvalInitialX = 'yes % evaluation of initial solution';
defopts.Restarts = '0 % number of restarts ';
defopts.IncPopSize = '2 % multiplier for population size before each restart';
defopts.PopSize = '(4 + floor(3*log(N))) % population size, lambda';
defopts.ParentNumber = 'floor(popsize/2) % popsize equals lambda';
defopts.RecombinationWeights = 'superlinear decrease % or linear, or equal';
defopts.Display = 'on % display messages like initial and final message';
defopts.Plotting = 'on % plot while running';
defopts.VerboseModulo = '100 % >=0, messaging after every i-th iteration';
defopts.Resume = 'no % resume former run from SaveFile';
defopts.Science = 'off % off==do some additional (minor) problem capturing';
defopts.Saving = 'on % [on|final|off][-v6] save data to file';
defopts.SaveModulo = '1 % if >1 record data less frequently after gen=100';
defopts.SaveTime = '25 % max. percentage of time for recording data';
defopts.SaveFileName = 'variablescmaes.mat'; % file name for saving
defopts.Seed = 'sum(100*clock) % evaluated if it is a string';
%qqqkkk
%defopts.varopt1 = ''; % 'for temporary and hacking purposes';
%defopts.varopt2 = ''; % 'for temporary and hacking purposes';
defopts.UserData = 'for saving data/comments associated with the run';
defopts.UserDat2 = ''; 'for saving data/comments associated with the run';
% ---------------------- Handling Input Parameters ----------------------
if nargin < 1 || isequal(fitfun, 'defaults') % pass default options
if nargin < 1
disp('Default options returned (type "help cmaes" for help).');
end
xmin = defopts;
if nargin > 1 % supplement second argument with default options
xmin = getoptions(xstart, defopts);
end
return;
end
if isequal(fitfun, 'displayoptions')
names = fieldnames(defopts);
for name = names'
disp([name{:} repmat(' ', 1, 20-length(name{:})) ': ''' defopts.(name{:}) '''']);
end
return;
end
input.fitfun = fitfun; % record used input
if isempty(fitfun)
% fitfun = definput.fitfun;
% warning(['Objective function not determined, ''' fitfun ''' used']);
error(['Objective function not determined']);
end
if ~ischar(fitfun)
error('first argument FUN must be a string');
end
if nargin < 2
xstart = [];
end
input.xstart = xstart;
if isempty(xstart)
% xstart = definput.xstart; % objective variables initial point
% warning('Initial search point, and problem dimension, not determined');
error('Initial search point, and problem dimension, not determined');
end
if nargin < 3
insigma = [];
end
if isa(insigma, 'struct')
error(['Third argument SIGMA must be (or eval to) a scalar '...
'or a column vector of size(X0,1)']);
end
input.sigma = insigma;
if isempty(insigma)
if size(myeval(xstart),2) > 1
insigma = std(xstart, 0, 2);
if any(insigma == 0)
error(['Initial search volume is zero, choose SIGMA or X0 appropriate']);
end
else
% will be captured later
% error(['Initial step sizes (SIGMA) not determined']);
end
end
% Compose options opts
if nargin < 4 || isempty(inopts) % no input options available
inopts = [];
opts = defopts;
else
opts = getoptions(inopts, defopts);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
counteval = 0; countevalNaN = 0;
irun = 0;
while irun <= myeval(opts.Restarts) % for-loop does not work with resume
irun = irun + 1;
% ------------------------ Initialization -------------------------------
% Handle resuming of old run
flgresume = myevalbool(opts.Resume);
if ~flgresume % not resuming a former run
% Assign settings from input parameters and options for myeval...
xmean = mean(myeval(xstart), 2); % in case of xstart is a population
N = size(xmean, 1); numberofvariables = N;
popsize = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1));
lambda = popsize;
insigma = myeval(insigma);
if all(size(insigma) == [N 2])
insigma = 0.5 * (insigma(:,2) - insigma(:,1));
end
else % flgresume is true, do resume former run
tmp = whos('-file', opts.SaveFileName);
for i = 1:length(tmp)
if strcmp(tmp(i).name, 'localopts');
error('Saved variables include variable "localopts", please remove');
end
end
local.opts = opts; % keep stopping and display options
local.varargin = varargin;
load(opts.SaveFileName);
varargin = local.varargin;
flgresume = 1;
% Overwrite old stopping and display options
opts.StopFitness = local.opts.StopFitness;
%%opts.MaxFunEvals = local.opts.MaxFunEvals;
%%opts.MaxIter = local.opts.MaxIter;
opts.StopFunEvals = local.opts.StopFunEvals;
opts.StopIter = local.opts.StopIter;
opts.TolX = local.opts.TolX;
opts.TolUpX = local.opts.TolUpX;
opts.TolFun = local.opts.TolFun;
opts.TolHistFun = local.opts.TolHistFun;
opts.StopOnWarnings = local.opts.StopOnWarnings;
opts.Display = local.opts.Display;
opts.Plotting = local.opts.Plotting;
opts.VerboseModulo = local.opts.VerboseModulo;
opts.Saving = local.opts.Saving;
opts.SaveModulo = local.opts.SaveModulo;
opts.SaveTime = local.opts.SaveTime;
clear local; % otherwise local would be overwritten during load
end
% Evaluate options
stopFitness = myeval(opts.StopFitness);
stopMaxFunEvals = myeval(opts.MaxFunEvals);
stopMaxIter = myeval(opts.MaxIter);
stopFunEvals = myeval(opts.StopFunEvals);
stopIter = myeval(opts.StopIter);
stopTolX = myeval(opts.TolX);
stopTolUpX = myeval(opts.TolUpX);
stopTolFun = myeval(opts.TolFun);
stopTolHistFun = myeval(opts.TolHistFun);
stopOnWarnings = myevalbool(opts.StopOnWarnings);
flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues);
flgEvalParallel = myevalbool(opts.EvalParallel);
flgdisplay = myevalbool(opts.Display);
flgplotting = myevalbool(opts.Plotting);
verbosemodulo = myeval(opts.VerboseModulo);
flgscience = myevalbool(opts.Science);
flgsaving = [];
strsaving = [];
if strfind(opts.Saving, '-v6')
i = strfind(opts.Saving, '%');
if isempty(i) || i == 0 || strfind(opts.Saving, '-v6') < i
strsaving = '-v6';
flgsaving = 1;
flgsavingfinal = 1;
end
end
if strncmp('final', opts.Saving, 5)
flgsaving = 0;
flgsavingfinal = 1;
end
if isempty(flgsaving)
flgsaving = myevalbool(opts.Saving);
flgsavingfinal = flgsaving;
end
savemodulo = myeval(opts.SaveModulo);
savetime = myeval(opts.SaveTime);
if (isfinite(stopFunEvals) || isfinite(stopIter)) && ~flgsaving
warning('To resume later the saving option needs to be set');
end
% Do more checking and initialization
if flgresume % resume is on
time.t0 = clock;
if flgdisplay
disp([' resumed from ' opts.SaveFileName ]);
end
if counteval >= stopMaxFunEvals
error(['MaxFunEvals exceeded, use StopFunEvals as stopping ' ...
'criterion before resume']);
end
if countiter >= stopMaxIter
error(['MaxIter exceeded, use StopIter as stopping criterion ' ...
'before resume']);
end
else
xmean = mean(myeval(xstart), 2); % evaluate xstart again, because of irun
maxdx = myeval(opts.DiffMaxChange); % maximal sensible variable change
mindx = myeval(opts.DiffMinChange); % minimal sensible variable change
% can both also be defined as Nx1 vectors
lbounds = myeval(opts.LBounds);
ubounds = myeval(opts.UBounds);
if length(lbounds) == 1
lbounds = repmat(lbounds, N, 1);
end
if length(ubounds) == 1
ubounds = repmat(ubounds, N, 1);
end
if isempty(insigma) % last chance to set insigma
if all(lbounds > -Inf) && all(ubounds < Inf)
if any(lbounds>=ubounds)
error('upper bound must be greater than lower bound');
end
insigma = 0.3*(ubounds-lbounds);
stopTolX = myeval(opts.TolX); % reevaluate these
stopTolUpX = myeval(opts.TolUpX);
else
error(['Initial step sizes (SIGMA) not determined']);
end
end
% Check all vector sizes
if size(xmean, 2) > 1 || size(xmean,1) ~= N
error(['intial search point should be a column vector of size ' ...
num2str(N)]);
elseif ~(all(size(insigma) == [1 1]) || all(size(insigma) == [N 1]))
error(['input parameter SIGMA should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
elseif size(stopTolX, 2) > 1 || ~ismember(size(stopTolX, 1), [1 N])
error(['option TolX should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
elseif size(stopTolUpX, 2) > 1 || ~ismember(size(stopTolUpX, 1), [1 N])
error(['option TolUpX should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
elseif size(maxdx, 2) > 1 || ~ismember(size(maxdx, 1), [1 N])
error(['option DiffMaxChange should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
elseif size(mindx, 2) > 1 || ~ismember(size(mindx, 1), [1 N])
error(['option DiffMinChange should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
elseif size(lbounds, 2) > 1 || ~ismember(size(lbounds, 1), [1 N])
error(['option lbounds should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
elseif size(ubounds, 2) > 1 || ~ismember(size(ubounds, 1), [1 N])
error(['option ubounds should be (or eval to) a scalar '...
'or a column vector of size ' num2str(N)] );
end
% Strategy internal parameter setting: Selection
mu = myeval(opts.ParentNumber); % number of parents/points for recombination
if strncmp(lower(opts.RecombinationWeights), 'equal', 3)
weights = ones(mu,1); % (mu_I,lambda)-CMA-ES
elseif strncmp(lower(opts.RecombinationWeights), 'linear', 3)
weights = mu+1-(1:mu)';
elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3)
weights = log(mu+1)-log(1:mu)'; % muXone array for weighted recombination
else
error(['Recombination weights to be "' opts.RecombinationWeights ...
'" is not implemented']);
end
mueff=sum(weights)^2/sum(weights.^2); % variance-effective size of mu
if mueff == lambda
error(['Combination of values for PopSize, ParentNumber and ' ...
' and RecombinationWeights is not reasonable']);
end
% Strategy internal parameter setting: Adaptation
cc = 4/(N+4); % time constant for cumulation for covariance matrix
cs = (mueff+2)/(N+mueff+3); % t-const for cumulation for step size control
mucov = mueff; % size of mu used for calculating learning rate ccov
ccov = (1/mucov) * 2/(N+1.41)^2 ... % learning rate for covariance matrix
+ (1-1/mucov) * min(1,(2*mueff-1)/((N+2)^2+mueff));
% ||ps|| is close to sqrt(mueff/N) for mueff large on linear fitness
damps = ... % damping for step size control, usually close to one
(1 + 2*max(0,sqrt((mueff-1)/(N+1))-1)) ... % limit sigma increase
* max(0.3, ... % reduce damps, if max. iteration number is small
1 - N/min(stopMaxIter,stopMaxFunEvals/lambda)) + cs;
%qqq hacking of a different parameter setting, e.g. for ccov or damps,
% can be done here.
% ccov = 0.0*ccov; disp(['CAVE: ccov=' num2str(ccov)]);
% Initialize dynamic internal state parameters
if any(insigma <= 0)
error(['Initial search volume (SIGMA) must be greater than zero']);
end
if max(insigma)/min(insigma) > 1e6
error(['Initial search volume (SIGMA) badly conditioned']);
end
sigma = max(insigma); % overall standard deviation
pc = zeros(N,1); ps = zeros(N,1); % evolution paths for C and sigma
if length(insigma) == 1
insigma = insigma * ones(N,1) ;
end
B = eye(N,N); % B defines the coordinate system
D = diag(insigma/max(insigma)); % diagonal matrix D defines the scaling
BD = B*D; % for speed up only
C = BD*(BD)'; % covariance matrix
fitness.hist=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values
fitness.histsel=NaN*ones(1,10+ceil(3*10*N/lambda)); % history of fitness values
% Initialize boundary handling
bnd.isactive = any(lbounds > -Inf) || any(ubounds < Inf);
if bnd.isactive
if any(lbounds>ubounds)
error('lower bound found to be greater than upper bound');
end
[xmean ti] = xintobounds(xmean, lbounds, ubounds); % just in case
if any(ti)
warning('Initial point was out of bounds, corrected');
end
bnd.weights = zeros(N,1); % weights for bound penalty
% scaling is better in axis-parallel case, worse in rotated
bnd.flgscale = 0; % scaling will be omitted if zero
if bnd.flgscale ~= 0
bnd.scale = diag(C)/mean(diag(C));
else
bnd.scale = ones(N,1);
end
idx = (lbounds > -Inf) | (ubounds < Inf);
if length(idx) == 1
idx = idx * ones(N,1);
end
bnd.isbounded = zeros(N,1);
bnd.isbounded(find(idx)) = 1;
maxdx = min(maxdx, (ubounds - lbounds)/2);
if any(sigma*sqrt(diag(C)) > maxdx)
fac = min(maxdx ./ sqrt(diag(C)))/sigma;
sigma = min(maxdx ./ sqrt(diag(C)));
warning(['Initial SIGMA multiplied by the factor ' num2str(fac) ...
', because it was larger than half' ...
' of one of the boundary intervals']);
end
idx = (lbounds > -Inf) & (ubounds < Inf);
dd = diag(C);
if any(5*sigma*sqrt(dd(idx)) < ubounds(idx) - lbounds(idx))
warning(['Initial SIGMA is, in at least one coordinate, ' ...
'much smaller than the '...
'given boundary intervals. For reasonable ' ...
'global search performance SIGMA should be ' ...
'between 0.2 and 0.5 of the bounded interval in ' ...
'each coordinate. If all coordinates have ' ...
'lower and upper bounds SIGMA can be empty']);
end
bnd.dfithist = 1; % delta fit for setting weights
bnd.aridxpoints = []; % remember complete outside points
bnd.arfitness = []; % and their fitness
bnd.validfitval = 0;
bnd.iniphase = 1;
end
% ooo initial feval, for output only
if irun == 1
out.solutions.bestever.x = xmean;
out.solutions.bestever.f = Inf; % for simpler comparison below
out.solutions.bestever.evals = counteval;
bestever = out.solutions.bestever;
end
if myevalbool(opts.EvalInitialX)
fitness.hist(1)=feval(fitfun, xmean, varargin{:});
fitness.histsel(1)=fitness.hist(1);
counteval = counteval + 1;
if fitness.hist(1) < out.solutions.bestever.f
out.solutions.bestever.x = xmean;
out.solutions.bestever.f = fitness.hist(1);
out.solutions.bestever.evals = counteval;
bestever = out.solutions.bestever;
end
else
fitness.hist(1)=NaN;
fitness.histsel(1)=NaN;
end
% initialize random number generator
if ischar(opts.Seed)
randn('state', eval(opts.Seed)); % random number generator state
else
randn('state', opts.Seed);
end
%qqq
% load(opts.SaveFileName, 'startseed');
% randn('state', startseed);
% disp(['SEED RELOADED FROM ' opts.SaveFileName]);
startseed = randn('state'); % for retrieving in saved variables
% Initialize further constants
chiN=N^0.5*(1-1/(4*N)+1/(21*N^2)); % expectation of
% ||N(0,I)|| == norm(randn(N,1))
weights = weights/sum(weights); % normalize recombination weights array
countiter = 0;
% Initialize records and output
if irun == 1
time.t0 = clock;
% per evaluation
% out.hist.AllSolutions.eval = 1;
% out.hist.AllSolutions.f = NaN;
% out.hist.AllSolutions.x = xmean; % most memory critical
% TODO: keep also median solution?
out.evals = counteval; % should be first entry
out.stopflag = {};
out.hist.evals = counteval;
out.hist.iterations = countiter;
out.hist.mean.x = xmean;
out.hist.mean.f = fitness.hist(1);
out.hist.mean.evals = counteval;
out.hist.recentbest.x = xmean;
out.hist.recentbest.f = fitness.hist(1); % reevaluations make an array
out.hist.recentbest.evals = counteval;
out.hist.recentworst.x = xmean;
out.hist.recentworst.f = fitness.hist(1); % reevaluations make an array
out.hist.recentworst.evals = counteval;
% Single Parameters
out.hist.param.evals = counteval;
out.hist.param.iterations = countiter;
out.hist.param.sigma = sigma;
out.hist.param.maxstd = sigma * sqrt(max(diag(C)));
out.hist.param.minstd = sigma * sqrt(min(diag(C)));
[muell out.hist.param.maxstdidx] = max(diag(C));
[muell out.hist.param.minstdidx] = min(diag(C));
out.hist.param.maxD = max(diag(D));
out.hist.param.minD = min(diag(D));
out.hist.param.comment = ['maxD=sqrt(max(EV)) where EV are' ...
' the eigenvalues of C and sigma^2*C is the' ...
' covariance matrix of the search distribution'];
% Parameter Arrays
out.histParamArr.evals = counteval;
out.histParamArr.iterations = countiter;
out.histParamArr.sigma = sigma; % for convenience and completeness
out.histParamArr.diagD = diag(D);
out.histParamArr.stds = sigma * sqrt(diag(C));
out.histParamArr.Bmax = B(:,out.hist.param.maxstdidx);
out.histParamArr.Bmin = B(:,out.hist.param.minstdidx);
out.histParamArr.comment = ...
['diagD = sort(sqrt(EV)), Bmax = eigenvector of largest ' ...
' eigenvalue (EV) of C'];
% out.x = 0;
% out.y1=[fitness.hist(1) sigma max(diag(D))/min(diag(D)) ...
% sigma*[max(diag(D)) min(diag(D))] fitness.hist(1)];
% out.y2=xmean'; out.y2a=xmean';
% out.y3=sigma*sqrt(diag(C))';
% out.y4=sort(diag(D))';
outiter = 0;
end
end % else flgresume
% Display initial message
if flgdisplay
if mu == 1
strw = '100';
elseif mu < 8
strw = [num2str(100*weights(1:end-1)','%.0f ') ...
num2str(100*weights(end)','%.0f') ];
else
strw = [num2str(100*weights(1:2)','%.2g ') ...
num2str(100*weights(3)','%.2g') '...' ...
num2str(100*weights(end-1:end)',' %.2g') ']%, '];
end
if irun > 1
strrun = [', run ' num2str(irun)];
else
strrun = '';
end
disp([' n=' num2str(N) ': (' num2str(mu) ',' ...
num2str(lambda) ')-CMA-ES(w=[' ...
strw ']%, ' ...
'mu_eff=' num2str(mueff,'%.1f') ...
') on function ' ...
(fitfun) strrun]);
end
% -------------------- Generation Loop --------------------------------
stopflag = {};
while isempty(stopflag)
countiter = countiter + 1;
flush;
% Generate and evaluate lambda offspring
fitness.raw = repmat(NaN, 1, lambda);
% parallel evaluation
if flgEvalParallel
arz = randn(N,lambda);
arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1)
% You may handle constraints here. You may either resample
% arz(:,k) and/or multiply it with a factor between -1 and 1
% (the latter will decrease the overall step size) and
% recalculate arx accordingly. Do not change arx or arz in any
% other way.
if ~bnd.isactive
arxvalid = arx;
else
arxvalid = xintobounds(arx, lbounds, ubounds);
end
% You may handle constraints here. You may copy and alter
% (columns of) arxvalid(:,k) only for the evaluation of the
% fitness function. arx and arxvalid should not be changed.
fitness.raw = feval(fitfun, arxvalid, varargin{:});
countevalNaN = countevalNaN + sum(isnan(fitness.raw));
counteval = counteval + sum(~isnan(fitness.raw));
end
% non-parallel evaluation and remaining NaN-values
for k=find(isnan(fitness.raw)),
% fitness.raw(k) = NaN;
tries = 0;
% Resample, until fitness is not NaN
while isnan(fitness.raw(k))
arz(:,k) = randn(N,1);
arx(:,k) = xmean + sigma * (BD * arz(:,k)); % Eq. (1)
% You may handle constraints here. You may either resample
% arz(:,k) and/or multiply it with a factor between -1 and 1
% (the latter will decrease the overall step size) and
% recalculate arx accordingly. Do not change arx or arz in any
% other way.
if ~bnd.isactive
arxvalid(:,k) = arx(:,k);
else
arxvalid(:,k) = xintobounds(arx(:,k), lbounds, ubounds);
end
% You may handle constraints here. You may copy and alter
% (columns of) arxvalid(:,k) only for the evaluation of the
% fitness function. arx should not be changed.
fitness.raw(k) = feval(fitfun, arxvalid(:,k), varargin{:});
tries = tries + 1;
if isnan(fitness.raw(k))
countevalNaN = countevalNaN + 1;
end
if mod(tries, 100) == 0
warning([num2str(tries) ...
' NaN objective function values at evaluation ' ...
num2str(counteval)]);
end
end
counteval = counteval + 1; % retries due to NaN are not counted
end
fitness.sel = fitness.raw;
% ----- handle boundaries -----
if 1 < 3 && bnd.isactive
% Get delta fitness values
val = myprctile(fitness.raw, [25 75]);
% more precise would be exp(mean(log(diag(C))))
val = (val(2) - val(1)) / N / mean(diag(C)) / sigma^2;
%val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ...
% / N / mean(diag(C)) / sigma^2;
% Catch non-sensible values
if ~isfinite(val)
warning('Non-finite fitness range');
val = max(bnd.dfithist);
elseif val == 0 % happens if all points are out of bounds
val = min(bnd.dfithist(bnd.dfithist>0));
elseif bnd.validfitval == 0 % first sensible val
bnd.dfithist = [];
bnd.validfitval = 1;
end
% Store delta fitness values
if length(bnd.dfithist) < 20+(3*N)/lambda
bnd.dfithist = [bnd.dfithist val];
else
bnd.dfithist = [bnd.dfithist(2:end) val];
end
[tx ti] = xintobounds(xmean, lbounds, ubounds);
% Set initial weights
if bnd.iniphase
if any(ti)
bnd.weights(find(bnd.isbounded)) = 2.0002 * median(bnd.dfithist);
if bnd.flgscale == 0 % scale only initial weights then
dd = diag(C);
idx = find(bnd.isbounded);
dd = dd(idx) / mean(dd); % remove mean scaling
bnd.weights(idx) = bnd.weights(idx) ./ dd;
end
if bnd.validfitval && countiter > 2
bnd.iniphase = 0;
end
end
end
% Increase weights
if 1 < 3 && any(ti) % any coordinate of xmean out of bounds
% judge distance of xmean to boundary
tx = xmean - tx;
idx = (ti ~= 0 & abs(tx) > 3*max(1,sqrt(N)/mueff) ...
* sigma*sqrt(diag(C))) ;
% only increase if xmean is moving away
idx = idx & (sign(tx) == sign(xmean - xold));
if ~isempty(idx) % increase
% the factor became 1.2 instead of 1.1, because
bnd.weights(idx) = 1.2^(max(1, mueff/10/N)) * bnd.weights(idx);
end
end
% Calculate scaling biased to unity, product is one
if bnd.flgscale ~= 0
bnd.scale = exp(0.9*(log(diag(C))-mean(log(diag(C)))));
end
% Assigned penalized fitness
bnd.arpenalty = (bnd.weights ./ bnd.scale)' * (arxvalid - arx).^2;
fitness.sel = fitness.raw + bnd.arpenalty;
end % handle boundaries
% ----- end handle boundaries -----
% Sort by fitness
[fitness.raw, fitness.idx] = sort(fitness.raw);
[fitness.sel, fitness.idxsel] = sort(fitness.sel); % minimization
fitness.hist(2:end) = fitness.hist(1:end-1); % record short history of
fitness.hist(1) = fitness.raw(1); % best fitness values
fitness.histsel(2:end) = fitness.histsel(1:end-1); % record short history of
fitness.histsel(1) = fitness.sel(1); % best fitness values
% Calculate new xmean, this is selection and recombination
xold = xmean; % for speed up of Eq. (2) and (3)
xmean = arx(:,fitness.idxsel(1:mu))*weights;
zmean = arz(:,fitness.idxsel(1:mu))*weights;%==D^-1*B'*(xmean-xold)/sigma
if mu == 1
fmean = fitness.sel(1);
else
fmean = NaN; % [] does not work in the latter assignment
% fmean = feval(fitfun, xintobounds(xmean, lbounds, ubounds), varargin{:});
% counteval = counteval + 1;
end
% Cumulation: update evolution paths
ps = (1-cs)*ps + (sqrt(cs*(2-cs)*mueff)) * (B*zmean); % Eq. (4)
hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.4 + 2/(N+1);
% hsig = norm(ps)/sqrt(1-(1-cs)^(2*countiter))/chiN < 1.5 + 1/(N-0.5);
% hsig = norm(ps) < 1.5 * sqrt(N);
% hsig = 1;
pc = (1-cc)*pc ...
+ hsig*(sqrt(cc*(2-cc)*mueff)/sigma) * (xmean-xold); % Eq. (2)
if hsig == 0
%disp([num2str(countiter) ' ' num2str(counteval) ' pc update stalled']);
end
% Adapt covariance matrix
if ccov > 0 % Eq. (3)
C = (1-ccov+(1-hsig)*ccov*cc*(2-cc)/mucov) * C ... % regard old matrix
+ ccov * (1/mucov) * pc*pc' ... % plus rank one update
+ ccov * (1-1/mucov) ... % plus rank mu update
* sigma^-2 * (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu)) ...
* diag(weights) * (arx(:,fitness.idxsel(1:mu))-repmat(xold,1,mu))';
end
if 1 < 2 && ~flgscience
% remove momentum in ps, if ps is large and fitness is getting worse.
% this should rarely happen.
% this is questionable in dynamic environments
if sum(ps.^2)/N > 1.5 + 10*(2/N)^.5 && ...
fitness.histsel(1) > max(fitness.histsel(2:3))
ps = ps * sqrt(N*(1+max(0,log(sum(ps.^2)/N))) / sum(ps.^2));
if flgdisplay
disp(['Momentum in ps removed at [niter neval]=' ...
num2str([countiter counteval]) ']']);
end
end
end
% Adapt sigma
sigma = sigma * exp((norm(ps)/chiN - 1)*cs/damps); % Eq. (5)
% Update B and D from C
if ccov > 0 && mod(countiter, 1/ccov/N/10) < 1
C=triu(C)+triu(C,1)'; % enforce symmetry
[B,D] = eig(C); % eigen decomposition, B==normalized eigenvectors
if any(~isfinite(diag(D)))
clear idx; % prevents error under octave
save(['tmp' opts.SaveFileName]);
error(['function eig returned non-finited eigenvalues, cond(C)=' ...
num2str(cond(C)) ]);
end
if any(any(~isfinite(diag(B))))
clear idx; % prevents error under octave
save(['tmp' opts.SaveFileName]);
error(['function eig returned non-finited eigenvectors, cond(C)=' ...
num2str(cond(C)) ]);
end
% limit condition of C to 1e14 + 1
if min(diag(D)) <= 0
if stopOnWarnings
stopflag(end+1) = {'warnconditioncov'};
else
warning(['Iteration ' num2str(countiter) ...
': Eigenvalue (smaller) zero']);
D(D<0) = 0;
tmp = max(diag(D))/1e14;
C = C + tmp*eye(N,N); D = D + tmp*eye(N,N);
end
end
if max(diag(D)) > 1e14*min(diag(D))
if stopOnWarnings
stopflag(end+1) = {'warnconditioncov'};
else
warning(['Iteration ' num2str(countiter) ': condition of C ' ...
'at upper limit' ]);
tmp = max(diag(D))/1e14 - min(diag(D));
C = C + tmp*eye(N,N); D = D + tmp*eye(N,N);
end
end
% Align order of magnitude of scales of sigma and C for nicer output
% needs to be carefully reviewed and tested yet
if 11 < 2 && sigma > 1e10*sqrt(max(diag(D)))
fac = sigma / sqrt(median(diag(D)));
sigma = sigma/fac;
pc = fac * pc;
C = fac^2 * C;
D = fac^2 * D;
end
D = diag(sqrt(diag(D))); % D contains standard deviations now
% D = D / prod(diag(D))^(1/N); C = C / prod(diag(D))^(2/N);
BD = B*D; % for speed up only
end % if mod
% ----- numerical error management -----
% Adjust maximal coordinate axis deviations
if any(sigma*sqrt(diag(C)) > maxdx)
sigma = min(maxdx ./ sqrt(diag(C)));
%warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
% 'deviation at upper limit of ' num2str(maxdx)]);
% stopflag(end+1) = {'maxcoorddev'};
end
% Adjust minimal coordinate axis deviations
if any(sigma*sqrt(diag(C)) < mindx)
sigma = max(mindx ./ sqrt(diag(C))) * exp(0.05+cs/damps);
%warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
% 'deviation at lower limit of ' num2str(mindx)]);
% stopflag(end+1) = {'mincoorddev'};;
end
% Adjust too low coordinate axis deviations
if any(xmean == xmean + 0.2*sigma*sqrt(diag(C)))
if stopOnWarnings
stopflag(end+1) = {'warnnoeffectcoord'};
else
warning(['Iteration ' num2str(countiter) ': coordinate axis std ' ...
'deviation too low' ]);
C = C + ccov * diag(diag(C) .* ...
(xmean == xmean + 0.2*sigma*sqrt(diag(C))));
sigma = sigma * exp(0.05+cs/damps);
end
end
% Adjust step size in case of (numerical) precision problem
if all(xmean == xmean ...
+ 0.1*sigma*BD(:,1+floor(mod(countiter,N))))
i = 1+floor(mod(countiter,N));
if stopOnWarnings
stopflag(end+1) = {'warnnoeffectaxis'};
else
warning(['Iteration ' num2str(countiter) ...
': main axis standard deviation ' ...
num2str(sigma*D(i,i)) ' has no effect' ]);
sigma = sigma * exp(0.2+cs/damps);
end
end
% Adjust step size in case of equal function values (flat fitness)
if fitness.sel(1) == fitness.sel(1+ceil(0.1+lambda/4))
if flgWarnOnEqualFunctionValues && stopOnWarnings
stopflag(end+1) = {'warnequalfunvals'};
else
if flgWarnOnEqualFunctionValues
warning(['Iteration ' num2str(countiter) ...
': equal function values f=' num2str(fitness.sel(1)) ...
' at maximal main axis sigma ' ...
num2str(sigma*max(diag(D)))]);
end
sigma = sigma * exp(0.2+cs/damps);
end
end
% Adjust step size in case of equal function values
if countiter > 2 && myrange([fitness.hist fitness.sel(1)]) == 0
if stopOnWarnings
stopflag(end+1) = {'warnequalfunvalhist'};
else
warning(['Iteration ' num2str(countiter) ...
': equal function values in history at maximal main ' ...
'axis sigma ' num2str(sigma*max(diag(D)))]);
sigma = sigma * exp(0.2+cs/damps);
end
end
% ----- end numerical error management -----
% Keep overall best solution
out.evals = counteval;
out.solutions.evals = counteval;
out.solutions.mean.x = xmean;
out.solutions.mean.f = fmean;
out.solutions.mean.evals = counteval;
out.solutions.recentbest.x = arxvalid(:, fitness.idx(1));
out.solutions.recentbest.f = fitness.raw(1);
out.solutions.recentbest.evals = counteval + fitness.idx(1) - lambda;
out.solutions.recentworst.x = arxvalid(:, fitness.idx(end));
out.solutions.recentworst.f = fitness.raw(end);
out.solutions.recentworst.evals = counteval + fitness.idx(end) - lambda;
if fitness.hist(1) < out.solutions.bestever.f
out.solutions.bestever.x = arxvalid(:, fitness.idx(1));
out.solutions.bestever.f = fitness.hist(1);
out.solutions.bestever.evals = counteval + fitness.idx(1) - lambda;
bestever = out.solutions.bestever;
end
% Set stop flag