-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmaes.m
3088 lines (2822 loc) · 115 KB
/
cmaes.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 3.61.beta, last change: April, 2012
% CMAES implements an Evolution Strategy with Covariance Matrix
% Adaptation (CMA-ES) for nonlinear function minimization. For
% introductory comments and copyright (GPL) see end of file (type
% 'type cmaes'). cmaes.m runs with MATLAB (Windows, Linux) and,
% without data logging and plotting, it should run under 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 an approximate 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 'frosen'. 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 some
% more output, where the struct SOLUTIONS.BESTEVER contains the overall
% best evaluated point X with function value F evaluated at evaluation
% count EVALS. The last output argument BESTEVER equals
% OUT.SOLUTIONS.BESTEVER. Moreover a history of solutions and
% parameters is written to files according to the Log-options.
%
% 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 LogFilenamePrefix
% option (by default 'outcmaes'). Also a run can be skipped.
% Given, for example, 'skip outcmaes run 2', skips the second run
% if option Restarts is at least 2, and another run will be started.
%
% To run the code completely silently set Disp, Save, and Log options
% to 0. With OPTS.LogModulo > 0 (1 by default) the most important
% data are written to ASCII files permitting to investigate the
% results (e.g. plot with function plotcmaesdat) even while CMAES is
% still running (which can be quite useful on expensive objective
% functions). When OPTS.SaveVariables==1 (default) everything is saved
% in file OPTS.SaveFilename (default 'variablescmaes.mat') allowing 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.
%
% In case of a noisy objective function (uncertainties) set
% OPTS.Noise.on = 1. This option interferes presumably with some
% termination criteria, because the step-size sigma will presumably
% not converge to zero anymore. If CMAES was provided with a
% fifth argument (P1 in the below example, which is passed to the
% objective function FUN), this argument is multiplied with the
% factor given in option Noise.alphaevals, each time the detected
% noise exceeds a threshold. This argument can be used within
% FUN, for example, as averaging number to reduce the noise level.
%
% OPTS.DiagonalOnly > 1 defines the number of initial iterations,
% where the covariance matrix remains diagonal and the algorithm has
% internally linear time complexity. OPTS.DiagonalOnly = 1 means
% keeping the covariance matrix always diagonal and this setting
% also exhibits linear space complexity. This can be particularly
% useful for dimension > 100. The default is OPTS.DiagonalOnly = 0.
%
% OPTS.CMA.active = 1 turns on "active CMA" with a negative update
% of the covariance matrix and checks for positive definiteness.
% OPTS.CMA.active = 2 does not check for pos. def. and is numerically
% faster. Active CMA usually speeds up the adaptation and might
% become a default in near future.
%
% The primary strategy parameter to play with is OPTS.PopSize, which
% can be increased from its default value. Increasing the population
% size (by default linked to increasing 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;
% opts.Restarts = 3; % doubles the popsize for each restart
% X = cmaes('myfun', 10*rand(10,1), 5, opts);
%
% searches 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.
% TODO:
% write dispcmaesdat for Matlab (and Octave)
% control savemodulo and plotmodulo via signals.par
cmaVersion = '3.62.beta';
% ----------- 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, possibly resume later';
defopts.StopIter = 'Inf % stop after resp. iteration, possibly 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.StopOnStagnation = 'on % stop when fitness stagnates for a long time';
% TODO: stagnation has four parameters for the period: min = 120, const = 30N/lam, rel = 0.2, max = 2e5
% defopts.StopOnStagnation = '[120 30*N/popsize 0.2 2e5] % [min const rel_iter max] measuring period';
defopts.StopOnWarnings = 'yes % ''no''==''off''==0, ''on''==''yes''==1 ';
defopts.StopOnEqualFunctionValues = '2 + N/3 % number of iterations';
% 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) % AKA mu, popsize equals lambda';
defopts.RecombinationWeights = 'superlinear decrease % or linear, or equal';
defopts.DiagonalOnly = '0*(1+100*N/sqrt(popsize))+(N>=1000) % C is diagonal for given iterations, 1==always';
defopts.Noise.on = '0 % uncertainty handling is off by default';
defopts.Noise.reevals = '1*ceil(0.05*lambda) % nb. of re-evaluated for uncertainty measurement';
defopts.Noise.theta = '0.5 % threshold to invoke uncertainty treatment'; % smaller: more likely to diverge
defopts.Noise.cum = '0.3 % cumulation constant for uncertainty';
defopts.Noise.cutoff = '2*lambda/3 % rank change cutoff for summation';
defopts.Noise.alphasigma = '1+2/(N+10) % factor for increasing sigma'; % smaller: slower adaptation
defopts.Noise.epsilon = '1e-7 % additional relative perturbation before reevaluation';
defopts.Noise.minmaxevals = '[1 inf] % min and max value of 2nd arg to fitfun, start value is 5th arg to cmaes';
defopts.Noise.alphaevals = '1+2/(N+10) % factor for increasing 2nd arg to fitfun';
defopts.Noise.callback = '[] % callback function when uncertainty threshold is exceeded';
% defopts.TPA = 0;
defopts.CMA.cs = '(mueff+2)/(N+mueff+3) % cumulation constant for step-size';
%qqq defopts.CMA.cs = (mueff^0.5)/(N^0.5+mueff^0.5) % the short time horizon version
defopts.CMA.damps = '1 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size';
% defopts.CMA.ccum = '4/(N+4) % cumulation constant for covariance matrix';
defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc';
defopts.CMA.ccov1 = '2 / ((N+1.3)^2+mueff) % learning rate for rank-one update';
defopts.CMA.ccovmu = '2 * (mueff-2+1/mueff) / ((N+2)^2+mueff) % learning rate for rank-mu update';
defopts.CMA.on = 'yes';
defopts.CMA.active = '0 % active CMA, 1: neg. updates with pos. def. check, 2: neg. updates';
flg_future_setting = 0; % testing for possible future variant(s)
if flg_future_setting
disp('in the future')
% damps setting from Brockhoff et al 2010
% this damps diverges with popsize 400:
% defopts.CMA.damps = '2*mueff/lambda + 0.3 + cs % damping for step-size';
% cmaeshtml('benchmarkszero', ones(20,1)*2, 5, o, 15);
% how about:
% defopts.CMA.damps = '2*mueff/lambda + 0.3 + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size';
defopts.CMA.damps = '0.5 + 0.5*min(1, (0.27*lambda/mueff-1)^2) + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size';
if 11 < 3
defopts.CMA.damps = '0.5 + 0.5*min(1,(lam_mirr/(0.159*lambda)-1)^2) + 2*max(0,sqrt((mueff-1)/(N+1))-1) + cs % damping for step-size';
defopts.mirrored_offspring = 'floor(0.5 + 0.159 * lambda)';
% TODO: this should also depend on diagonal option!?
defopts.CMA.active = 'floor(int8(lam_mirr>0)) % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
end
% ccum adjusted for large mueff, better on schefelmult?
% TODO: this should also depend on diagonal option!?
defopts.CMA.ccum = '(4 + mueff/N) / (N+4 + 2*mueff/N) % cumulation constant for pc';
defopts.CMA.active = '1 % active CMA 1: neg. updates with pos. def. check, 2: neg. updates';
end
defopts.Resume = 'no % resume former run from SaveFile';
defopts.Science = 'on % off==do some additional (minor) problem capturing, NOT IN USE';
defopts.ReadSignals = 'on % from file signals.par for termination, yet a stumb';
defopts.Seed = 'sum(100*clock) % evaluated if it is a string';
defopts.DispFinal = 'on % display messages like initial and final message';
defopts.DispModulo = '100 % [0:Inf], disp messages after every i-th iteration';
defopts.SaveVariables = 'on % [on|final|off][-v6] save variables to .mat file';
defopts.SaveFilename = 'variablescmaes.mat % save all variables, see SaveVariables';
defopts.LogModulo = '1 % [0:Inf] if >1 record data less frequently after gen=100';
defopts.LogTime = '25 % [0:100] max. percentage of time for recording data';
defopts.LogFilenamePrefix = 'outcmaes % files for output data';
defopts.LogPlot = 'off % plot while running using output data files';
defopts.BaseDirectory = '% Base directory to save variables in';
%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
inputVars.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
inputVars.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
inputVars.sigma = insigma;
if isempty(insigma)
if all(size(myeval(xstart)) > 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
jj = strsplit(opts.BaseDirectory,'%');
if ~isempty(jj)
opts.BaseDirectory = jj{1};
end
ii = strfind(opts.SaveFilename, '%'); % remove everything after comment
if ~isempty(ii)
opts.SaveFilename = [opts.BaseDirectory filesep opts.SaveFilename(1:ii(1)-1)];
end
if ~exist(opts.SaveFilename,'file')
opts.Resume = 'no';
end
opts.SaveFilename = deblank(opts.SaveFilename); % remove trailing white spaces
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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);
xmean = myeval(xstart);
if all(size(xmean) > 1)
xmean = mean(xmean, 2); % in case if xstart is a population
elseif size(xmean, 2) > 1
xmean = xmean';
end
if ~flgresume % not resuming a former run
% Assign settings from input parameters and options for myeval...
N = size(xmean, 1); numberofvariables = N;
lambda0 = floor(myeval(opts.PopSize) * myeval(opts.IncPopSize)^(irun-1));
% lambda0 = floor(myeval(opts.PopSize) * 3^floor((irun-1)/2));
popsize = lambda0;
lambda = lambda0;
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 ii = 1:length(tmp)
if strcmp(tmp(ii).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.StopOnStagnation = local.opts.StopOnStagnation;
opts.StopOnWarnings = local.opts.StopOnWarnings;
opts.ReadSignals = local.opts.ReadSignals;
opts.DispFinal = local.opts.DispFinal;
opts.LogPlot = local.opts.LogPlot;
opts.DispModulo = local.opts.DispModulo;
opts.SaveVariables = local.opts.SaveVariables;
opts.LogModulo = local.opts.LogModulo;
opts.LogTime = local.opts.LogTime;
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);
if flgresume
stopIter = stopIter + countiter
end
stopTolX = myeval(opts.TolX);
stopTolUpX = myeval(opts.TolUpX);
stopTolFun = myeval(opts.TolFun);
stopTolHistFun = myeval(opts.TolHistFun);
stopOnStagnation = myevalbool(opts.StopOnStagnation);
stopOnWarnings = myevalbool(opts.StopOnWarnings);
flgreadsignals = myevalbool(opts.ReadSignals);
flgWarnOnEqualFunctionValues = myevalbool(opts.WarnOnEqualFunctionValues);
flgEvalParallel = myevalbool(opts.EvalParallel);
stopOnEqualFunctionValues = myeval(opts.StopOnEqualFunctionValues);
arrEqualFunvals = zeros(1, 10+N);
flgDiagonalOnly = myeval(opts.DiagonalOnly);
flgActiveCMA = myeval(opts.CMA.active);
noiseHandling = myevalbool(opts.Noise.on);
noiseMinMaxEvals = myeval(opts.Noise.minmaxevals);
noiseAlphaEvals = myeval(opts.Noise.alphaevals);
noiseCallback = myeval(opts.Noise.callback);
flgdisplay = myevalbool(opts.DispFinal);
flgplotting = myevalbool(opts.LogPlot);
verbosemodulo = myeval(opts.DispModulo);
flgscience = myevalbool(opts.Science);
flgsaving = [];
strsaving = [];
if strfind(opts.SaveVariables, '-v6')
ii = strfind(opts.SaveVariables, '%');
if isempty(ii) || ii == 0 || strfind(opts.SaveVariables, '-v6') < ii
strsaving = '-v6';
flgsaving = 1;
flgsavingfinal = 1;
end
end
if strncmp('final', opts.SaveVariables, 5)
flgsaving = 0;
flgsavingfinal = 1;
end
if isempty(flgsaving)
flgsaving = myevalbool(opts.SaveVariables);
flgsavingfinal = flgsaving;
end
savemodulo = myeval(opts.LogModulo);
savetime = myeval(opts.LogTime);
ii = strfind(opts.LogFilenamePrefix, ' '); % remove everything after white space
if ~isempty(ii)
opts.LogFilenamePrefix = opts.LogFilenamePrefix(1:ii(1)-1);
end
% TODO here silent option? set disp, save and log options to 0
%--------------------------------------------------------------
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 % flgresume
% 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
% 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
diagD = insigma/max(insigma); % diagonal matrix D defines the scaling
diagC = diagD.^2;
if flgDiagonalOnly ~= 1 % use at some point full covariance matrix
B = eye(N,N); % B defines the coordinate system
BD = B.*repmat(diagD',N,1); % B*D for speed up only
C = diag(diagC); % covariance matrix == BD*(BD)'
end
if flgDiagonalOnly
B = 1;
end
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
fitness.histbest=[]; % history of fitness values
fitness.histmedian=[]; % 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 = diagC/mean(diagC);
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(diagC) > maxdx)
fac = min(maxdx ./ sqrt(diagC))/sigma;
sigma = min(maxdx ./ sqrt(diagC));
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 = diagC;
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))
countiter = 0;
% Initialize records and output
if irun == 1
time.t0 = clock;
% TODO: keep also median solution?
out.evals = counteval; % should be first entry
out.stopflag = {};
outiter = 0;
% Write headers to output data files
filenameprefix = opts.LogFilenamePrefix;
if savemodulo && savetime
filenames = {};
filenames(end+1) = {'axlen'};
filenames(end+1) = {'fit'};
filenames(end+1) = {'stddev'};
filenames(end+1) = {'xmean'};
filenames(end+1) = {'xrecentbest'};
str = [' (startseed=' num2str(startseed(2)) ...
', ' num2str(clock, '%d/%02d/%d %d:%d:%2.2f') ')'];
for namecell = filenames(:)'
name = namecell{:};
[fid, err] = fopen([opts.BaseDirectory filesep filenameprefix name '.dat'], 'w');
if fid < 1 % err ~= 0
warning(['could not open ' filenameprefix name '.dat']);
filenames(find(strcmp(filenames,name))) = [];
else
% fprintf(fid, '%s\n', ...
% ['<CMAES-OUTPUT version="' cmaVersion '">']);
% fprintf(fid, [' <NAME>' name '</NAME>\n']);
% fprintf(fid, [' <DATE>' date() '</DATE>\n']);
% fprintf(fid, ' <PARAMETERS>\n');
% fprintf(fid, [' dimension=' num2str(N) '\n']);
% fprintf(fid, ' </PARAMETERS>\n');
% different cases for DATA columns annotations here
% fprintf(fid, ' <DATA');
if strcmp(name, 'axlen')
fprintf(fid, ['%% columns="iteration, evaluation, sigma, ' ...
'max axis length, min axis length, ' ...
'all principal axes lengths (sorted square roots ' ...
'of eigenvalues of C)"' str]);
elseif strcmp(name, 'fit')
fprintf(fid, ['%% columns="iteration, evaluation, sigma, axis ratio, bestever,' ...
' best, median, worst fitness function value,' ...
' further objective values of best"' str]);
elseif strcmp(name, 'stddev')
fprintf(fid, ['%% columns=["iteration, evaluation, sigma, void, void, ' ...
'stds==sigma*sqrt(diag(C))"' str]);
elseif strcmp(name, 'xmean')
fprintf(fid, ['%% columns="iteration, evaluation, void, ' ...
'void, void, xmean"' str]);
elseif strcmp(name, 'xrecentbest')
fprintf(fid, ['%% columns="iteration, evaluation, fitness, ' ...
'void, void, xrecentbest"' str]);
end
fprintf(fid, '\n'); % DATA
if strcmp(name, 'xmean')
fprintf(fid, '%ld %ld 0 0 0 ', 0, counteval);
% fprintf(fid, '%ld %ld 0 0 %e ', countiter, counteval, fmean);
%qqq fprintf(fid, msprintf('%e ', genophenotransform(out.genopheno, xmean)) + '\n');
fprintf(fid, '%e ', xmean);
fprintf(fid, '\n');
end
fclose(fid);
clear fid; % preventing
end
end % for files
end % savemodulo
end % irun == 1
end % else flgresume
% -------------------- Generation Loop --------------------------------
stopflag = {};
while isempty(stopflag)
% set internal parameters
if countiter == 0 || lambda ~= lambda_last
if countiter > 0 && floor(log10(lambda)) ~= floor(log10(lambda_last)) ...
&& flgdisplay
disp([' lambda = ' num2str(lambda)]);
lambda_hist(:,end+1) = [countiter+1; lambda];
else
lambda_hist = [countiter+1; lambda];
end
lambda_last = lambda;
% 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+0.5-(1:mu)';
elseif strncmp(lower(opts.RecombinationWeights), 'superlinear', 3)
% use (lambda+1)/2 as reference if mu < lambda/2
weights = log(max(mu, lambda/2) + 1/2)-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
weights = weights/sum(weights); % normalize recombination weights array
if mueff == lambda
error(['Combination of values for PopSize, ParentNumber and ' ...
' and RecombinationWeights is not reasonable']);
end
% Strategy internal parameter setting: Adaptation
cc = myeval(opts.CMA.ccum); % time constant for cumulation for covariance matrix
cs = myeval(opts.CMA.cs);
% old way TODO: remove this at some point
% 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*mucov-1)/((N+2)^2+mucov));
% new way
if myevalbool(opts.CMA.on)
ccov1 = myeval(opts.CMA.ccov1);
ccovmu = min(1-ccov1, myeval(opts.CMA.ccovmu));
else
ccov1 = 0;
ccovmu = 0;
end
% flgDiagonalOnly = -lambda*4*1/ccov; % for ccov==1 it is not needed
% 0 : C will never be diagonal anymore
% 1 : C will always be diagonal
% >1: C is diagonal for first iterations, set to 0 afterwards
if flgDiagonalOnly < 1
flgDiagonalOnly = 0;
end
if flgDiagonalOnly
ccov1_sep = min(1, ccov1 * (N+1.5) / 3);
ccovmu_sep = min(1-ccov1_sep, ccovmu * (N+1.5) / 3);
elseif N > 98 && flgdisplay && countiter == 0
disp('consider option DiagonalOnly for high-dimensional problems');
end
% ||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;
damps = myeval(opts.CMA.damps);
if noiseHandling
noiseReevals = min(myeval(opts.Noise.reevals), lambda);
noiseAlpha = myeval(opts.Noise.alphasigma);
noiseEpsilon = myeval(opts.Noise.epsilon);
noiseTheta = myeval(opts.Noise.theta);
noisecum = myeval(opts.Noise.cum);
noiseCutOff = myeval(opts.Noise.cutoff); % arguably of minor relevance
else
noiseReevals = 0; % more convenient in later coding
end
%qqq hacking of a different parameter setting, e.g. for ccov or damps,
% can be done here, but is not necessary anymore, see opts.CMA.
% ccov1 = 0.0*ccov1; disp(['CAVE: ccov1=' num2str(ccov1)]);
% ccovmu = 0.0*ccovmu; disp(['CAVE: ccovmu=' num2str(ccovmu)]);
% damps = inf*damps; disp(['CAVE: damps=' num2str(damps)]);
% cc = 1; disp(['CAVE: cc=' num2str(cc)]);
end
% Display initial message
if countiter == 0 && flgdisplay
if mu == 1
strw = '100';
elseif mu < 8
strw = [sprintf('%.0f', 100*weights(1)) ...
sprintf(' %.0f', 100*weights(2:end)')];
else
strw = [sprintf('%.2g ', 100*weights(1:2)') ...
sprintf('%.2g', 100*weights(3)') '...' ...
sprintf(' %.2g', 100*weights(end-1:end)') ']%, '];
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]);
if flgDiagonalOnly == 1
disp(' C is diagonal');
elseif flgDiagonalOnly
disp([' C is diagonal for ' num2str(floor(flgDiagonalOnly)) ' iterations']);
end
end
flush;
countiter = countiter + 1;
% Generate and evaluate lambda offspring
fitness.raw = repmat(NaN, 1, lambda + noiseReevals);
% parallel evaluation
if flgEvalParallel
arz = randn(N,lambda);
if ~flgDiagonalOnly
arx = repmat(xmean, 1, lambda) + sigma * (BD * arz); % Eq. (1)
else
arx = repmat(xmean, 1, lambda) + repmat(sigma * diagD, 1, lambda) .* arz;
end
if noiseHandling
if noiseEpsilon == 0
arx = [arx arx(:,1:noiseReevals)];
elseif flgDiagonalOnly
arx = [arx arx(:,1:noiseReevals) + ...
repmat(noiseEpsilon * sigma * diagD, 1, noiseReevals) ...
.* randn(N,noiseReevals)];
else
arx = [arx arx(:,1:noiseReevals) + ...
noiseEpsilon * sigma * ...
(BD * randn(N,noiseReevals))];
end
end
% 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
% set also the reevaluated solution to NaN
fitness.raw(lambda + find(isnan(fitness.raw(1:noiseReevals)))) = NaN;
for k=find(isnan(fitness.raw)),
% fitness.raw(k) = NaN;
tries = flgEvalParallel; % in parallel case this is the first re-trial
% Resample, until fitness is not NaN
while isnan(fitness.raw(k))
if k <= lambda % regular samples (not the re-evaluation-samples)
arz(:,k) = randn(N,1); % (re)sample
if flgDiagonalOnly
arx(:,k) = xmean + sigma * diagD .* arz(:,k); % Eq. (1)
else
arx(:,k) = xmean + sigma * (BD * arz(:,k)); % Eq. (1)
end
else % re-evaluation solution with index > lambda
if flgDiagonalOnly
arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * diagD .* randn(N,1);
else
arx(:,k) = arx(:,k-lambda) + (noiseEpsilon * sigma) * (BD * randn(N,1));
end
end
% 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(diagC)))
val = (val(2) - val(1)) / N / mean(diagC) / sigma^2;
%val = (myprctile(fitness.raw, 75) - myprctile(fitness.raw, 25)) ...
% / N / mean(diagC) / 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)); % seems not to make sense, given all solutions are out of bounds
elseif bnd.validfitval == 0 % flag that first sensible val was found
bnd.dfithist = [];
bnd.validfitval = 1;
end