-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmaes.cpp
executable file
·2936 lines (2624 loc) · 89.9 KB
/
cmaes.cpp
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
/* --------------------------------------------------------- */
/* --- File: cmaes.c -------- Author: Nikolaus Hansen --- */
/* --------------------------------------------------------- */
/*
CMA-ES for non-linear function minimization.
Copyright 1996, 2003, 2007 Nikolaus Hansen
e-mail: hansen .AT. bionik.tu-berlin.de
hansen .AT. lri.fr
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2,
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* --- Changes : ---
03/03/21: argument const double *rgFunVal of
cmaes_ReestimateDistribution() was treated incorrectly.
03/03/29: restart via cmaes_resume_distribution() implemented.
03/03/30: Always max std dev / largest axis is printed first.
03/08/30: Damping is adjusted for large mueff.
03/10/30: Damping is adjusted for large mueff always.
04/04/22: Cumulation time and damping for step size adjusted.
No iniphase but conditional update of pc.
05/03/15: in ccov-setting mucov replaced by mueff.
05/10/05: revise comment on resampling in example.c
05/10/13: output of "coorstddev" changed from sigma * C[i][i]
to correct sigma * sqrt(C[i][i]).
05/11/09: Numerical problems are not anymore handled by increasing
sigma, but lead to satisfy a stopping criterion in
cmaes_Test().
05/11/09: Update of eigensystem and test for numerical problems
moved right before sampling.
06/02/24: Non-ansi array definitions replaced (thanks to Marc
Toussaint).
06/02/25: Overflow in time measurement for runs longer than
2100 seconds. This could lead to stalling the
covariance matrix update for long periods.
Time measurement completely rewritten.
06/02/26: Included population size lambda as parameter to
cmaes_init (thanks to MT).
06/02/26: Allow no initial reading/writing of parameters via
"non" and "writeonly" keywords for input parameter
filename in cmaes_init.
06/02/27: Optimized code regarding time spent in updating the
covariance matrix in function Adapt_C2().
07/08/03: clean up and implementation of an exhaustive test
of the eigendecomposition (via #ifdef for now)
07/08/04: writing of output improved
07/08/xx: termination criteria revised and more added,
damp replaced by damps=damp*cs, documentation improved.
Interface significantly changed, evaluateSample function
and therefore the function pointer argument removed.
Renaming of functions in accordance with Java code.
Clean up of parameter names, mainly in accordance with
Matlab conventions. Most termination criteria can be
changed online now. Many more small changes, but not in
the core procedure.
07/10/29: ReSampleSingle() got a better interface. ReSampleSingle()
is now ReSampleSingle_old only for backward
compatibility. Also fixed incorrect documentation. The new
function SampleSingleInto() has an interface similar to
the old ReSampleSingle(), but is not really necessary.
07/11/20: bug: stopMaxIter did not translate into the correct default
value but into -1 as default. This lead to a too large
damps and the termination test became true from the first
iteration. (Thanks to Michael Calonder)
07/11/20: new default stopTolFunHist = 1e-13; (instead of zero)
08/09/26: initial diagonal covariance matrix in code, but not
yet in interface
08/09/27: diagonalCovarianceMatrix option in initials.par provided
08/10/17: uncertainty handling implemented in example3.c.
PerturbSolutionInto() provides the optional small
perturbations before reevaluation.
Wish List
o as writing time is measure for all files at once, the display
cannot be independently written to a file via signals.par, while
this would be desirable.
o clean up sorting of eigenvalues and vectors which is done repeatedly.
o either use cmaes_Get() in cmaes_WriteToFilePtr(): revise the
cmaes_write that all keywords available with get and getptr are
recognized. Also revise the keywords, keeping backward
compatibility. (not only) for this it would be useful to find a
way how cmaes_Get() signals an unrecognized keyword. For GetPtr
it can return NULL.
o or break cmaes_Get() into single getter functions, being a nicer
interface, and compile instead of runtime error, and faster. For
file signals.par it does not help.
o writing data depending on timing in a smarter way, e.g. using 10%
of all time. First find out whether clock() is useful for measuring
disc writing time and then timings_t class can be utilized.
For very large dimension the default of 1 seconds waiting might
be too small.
o allow modification of best solution depending on delivered f(xmean)
o re-write input and output procedures
*/
#include <math.h> /* sqrt() */
#include <stddef.h> /* size_t */
#include <stdlib.h> /* NULL, free */
#include <string.h> /* strlen() */
#include <stdio.h> /* sprintf(), NULL? */
#include "cmaes_interface.h" /* <time.h> via cmaes.h */
/* --------------------------------------------------------- */
/* ------------------- Declarations ------------------------ */
/* --------------------------------------------------------- */
/* ------------------- External Visibly -------------------- */
/* see cmaes_interface.h for those, not listed here */
long random_init(random_t *, long unsigned seed /* 0==clock */);
void random_exit(random_t *);
double random_Gauss(random_t *); /* (0,1)-normally distributed */
double random_Uniform(random_t *);
long random_Start(random_t *, long unsigned seed /* 0==1 */);
void timings_init(timings_t *timing);
void timings_start(timings_t *timing); /* fields totaltime and tictoctime */
double timings_update(timings_t *timing);
void timings_tic(timings_t *timing);
double timings_toc(timings_t *timing);
void readpara_init (readpara_t *, int dim, int seed, const double * xstart,
const double * sigma, int lambda, const char * filename);
void readpara_exit(readpara_t *);
void readpara_ReadFromFile(readpara_t *, const char *szFileName);
void readpara_SupplementDefaults(readpara_t *);
void readpara_SetWeights(readpara_t *, const char * mode);
void readpara_WriteToFile(readpara_t *, const char *filenamedest,
const char *parafilesource);
double const * cmaes_SetMean(cmaes_t *, const double *xmean);
double * cmaes_PerturbSolutionInto(cmaes_t *t, double *xout,
double const *xin, double eps);
void cmaes_WriteToFile(cmaes_t *, const char *key, const char *name);
void cmaes_WriteToFileAW(cmaes_t *t, const char *key, const char *name,
char * append);
void cmaes_WriteToFilePtr(cmaes_t *, const char *key, FILE *fp);
void cmaes_ReadFromFilePtr(cmaes_t *, FILE *fp);
void cmaes_FATAL(char const *s1, char const *s2,
char const *s3, char const *s4);
/* ------------------- Locally visibly ----------------------- */
static char * getTimeStr(void);
static void TestMinStdDevs( cmaes_t *);
/* static void WriteMaxErrorInfo( cmaes_t *); */
static void Eigen( int N, double **C, double *diag, double **Q,
double *rgtmp);
static int Check_Eigen( int N, double **C, double *diag, double **Q);
static void QLalgo2 (int n, double *d, double *e, double **V);
static void Householder2(int n, double **V, double *d, double *e);
static void Adapt_C2(cmaes_t *t, int hsig);
static void FATAL(char const *sz1, char const *s2,
char const *s3, char const *s4);
static void ERRORMESSAGE(char const *sz1, char const *s2,
char const *s3, char const *s4);
static void Sorted_index( const double *rgFunVal, int *index, int n);
static int SignOfDiff( const void *d1, const void * d2);
static double douSquare(double);
static double rgdouMax( const double *rgd, int len);
static double rgdouMin( const double *rgd, int len);
static double douMax( double d1, double d2);
static double douMin( double d1, double d2);
static int intMin( int i, int j);
static int MaxIdx( const double *rgd, int len);
static int MinIdx( const double *rgd, int len);
static double myhypot(double a, double b);
static double * new_double( int n);
static void * new_void( int n, size_t size);
/* --------------------------------------------------------- */
/* ---------------- Functions: cmaes_t --------------------- */
/* --------------------------------------------------------- */
static char *
getTimeStr(void) {
time_t tm = time(NULL);
static char s[33];
/* get time */
strncpy(s, ctime(&tm), 24); /* TODO: hopefully we read something useful */
s[24] = '\0'; /* cut the \n */
return s;
}
char *
cmaes_SayHello(cmaes_t *t)
{
/* write initial message */
sprintf(t->sOutString,
"(%d,%d)-CMA-ES(mu_eff=%.1f), Ver=\"%s\", dimension=%d, diagonalIterations=%ld, randomSeed=%d (%s)",
t->sp.mu, t->sp.lambda, t->sp.mueff, t->version, t->sp.N, (long)t->sp.diagonalCov,
t->sp.seed, getTimeStr());
return t->sOutString;
}
double *
cmaes_init(cmaes_t *t, /* "this" */
int dimension,
double *inxstart,
double *inrgstddev, /* initial stds */
long int inseed,
int lambda,
const char *input_parameter_filename)
{
int i, j, N;
double dtest, trace;
t->version = "3.10.00.beta";
readpara_init (&t->sp, dimension, inseed, inxstart, inrgstddev,
lambda, input_parameter_filename);
t->sp.seed = random_init( &t->rand, (unsigned) t->sp.seed);
N = t->sp.N; /* for convenience */
/* initialization */
for (i = 0, trace = 0.; i < N; ++i)
trace += t->sp.rgInitialStds[i]*t->sp.rgInitialStds[i];
t->sigma = sqrt(trace/N); /* t->sp.mueff/(0.2*t->sp.mueff+sqrt(N)) * sqrt(trace/N); */
t->chiN = sqrt((double) N) * (1. - 1./(4.*N) + 1./(21.*N*N));
t->flgEigensysIsUptodate = 1;
t->flgCheckEigen = 0;
t->genOfEigensysUpdate = 0;
timings_init(&t->eigenTimings);
t->flgIniphase = 0; /* do not use iniphase, hsig does the job now */
t->flgresumedone = 0;
t->flgStop = 0;
for (dtest = 1.; dtest && dtest < 1.1 * dtest; dtest *= 2.)
if (dtest == dtest + 1.)
break;
t->dMaxSignifKond = dtest / 1000.; /* not sure whether this is really save, 100 does not work well enough */
t->gen = 0;
t->countevals = 0;
t->state = 0;
t->dLastMinEWgroesserNull = 1.0;
t->printtime = t->writetime = t->firstwritetime = t->firstprinttime = 0;
t->rgpc = new_double(N);
t->rgps = new_double(N);
t->rgdTmp = new_double(N+1);
t->rgBDz = new_double(N);
t->rgxmean = new_double(N+2); t->rgxmean[0] = N; ++t->rgxmean;
t->rgxold = new_double(N+2); t->rgxold[0] = N; ++t->rgxold;
t->rgxbestever = new_double(N+3); t->rgxbestever[0] = N; ++t->rgxbestever;
t->rgout = new_double(N+2); t->rgout[0] = N; ++t->rgout;
t->rgD = new_double(N);
t->C = (double**)new_void(N, sizeof(double*));
t->B = (double**)new_void(N, sizeof(double*));
t->publicFitness = new_double(t->sp.lambda);
t->rgFuncValue = new_double(t->sp.lambda+1);
t->rgFuncValue[0]=t->sp.lambda; ++t->rgFuncValue;
t->arFuncValueHist = new_double(10+(int)ceil(3.*10.*N/t->sp.lambda)+1);
t->arFuncValueHist[0] = (double)(10+(int)ceil(3.*10.*N/t->sp.lambda));
t->arFuncValueHist++;
for (i = 0; i < N; ++i) {
t->C[i] = new_double(i+1);
t->B[i] = new_double(N);
}
t->index = (int *) new_void(t->sp.lambda, sizeof(int));
for (i = 0; i < t->sp.lambda; ++i)
t->index[i] = i; /* should not be necessary */
t->rgrgx = (double **)new_void(t->sp.lambda, sizeof(double*));
for (i = 0; i < t->sp.lambda; ++i) {
t->rgrgx[i] = new_double(N+2);
t->rgrgx[i][0] = N;
t->rgrgx[i]++;
}
/* Initialize newed space */
for (i = 0; i < N; ++i)
for (j = 0; j < i; ++j)
t->C[i][j] = t->B[i][j] = t->B[j][i] = 0.;
for (i = 0; i < N; ++i)
{
t->B[i][i] = 1.;
t->C[i][i] = t->rgD[i] = t->sp.rgInitialStds[i] * sqrt(N / trace);
t->C[i][i] *= t->C[i][i];
t->rgpc[i] = t->rgps[i] = 0.;
}
t->minEW = rgdouMin(t->rgD, N); t->minEW = t->minEW * t->minEW;
t->maxEW = rgdouMax(t->rgD, N); t->maxEW = t->maxEW * t->maxEW;
t->maxdiagC=t->C[0][0]; for(i=1;i<N;++i) if(t->maxdiagC<t->C[i][i]) t->maxdiagC=t->C[i][i];
t->mindiagC=t->C[0][0]; for(i=1;i<N;++i) if(t->mindiagC>t->C[i][i]) t->mindiagC=t->C[i][i];
/* set xmean */
for (i = 0; i < N; ++i)
t->rgxmean[i] = t->rgxold[i] = t->sp.xstart[i];
/* use in case xstart as typicalX */
if (t->sp.typicalXcase)
for (i = 0; i < N; ++i)
t->rgxmean[i] += t->sigma * t->rgD[i] * random_Gauss(&t->rand);
if (strcmp(t->sp.resumefile, "_no_") != 0)
cmaes_resume_distribution(t, t->sp.resumefile);
return (t->publicFitness);
} /* cmaes_init() */
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
void
cmaes_resume_distribution(cmaes_t *t, char *filename)
{
int i, j, res, n;
double d;
FILE *fp = fopen( filename, "r");
if(fp == NULL) {
ERRORMESSAGE("cmaes_resume_distribution(): could not open '",
filename, "'",0);
return;
}
/* count number of "resume" entries */
i = 0; res = 0;
while (1) {
if ((res = fscanf(fp, " resume %lg", &d)) == EOF)
break;
else if (res==0)
fscanf(fp, " %*s");
else if(res > 0)
i += 1;
}
/* go to last "resume" entry */
n = i; i = 0; res = 0; rewind(fp);
while (i<n) {
if ((res = fscanf(fp, " resume %lg", &d)) == EOF)
FATAL("cmaes_resume_distribution(): Unexpected error, bug",0,0,0);
else if (res==0)
fscanf(fp, " %*s");
else if(res > 0)
++i;
}
if (d != t->sp.N)
FATAL("cmaes_resume_distribution(): Dimension numbers do not match",0,0,0);
/* find next "xmean" entry */
while (1) {
if ((res = fscanf(fp, " xmean %lg", &d)) == EOF)
FATAL("cmaes_resume_distribution(): 'xmean' not found",0,0,0);
else if (res==0)
fscanf(fp, " %*s");
else if(res > 0)
break;
}
/* read xmean */
t->rgxmean[0] = d; res = 1;
for(i = 1; i < t->sp.N; ++i)
res += fscanf(fp, " %lg", &t->rgxmean[i]);
if (res != t->sp.N)
FATAL("cmaes_resume_distribution(): xmean: dimensions differ",0,0,0);
/* find next "path for sigma" entry */
while (1) {
if ((res = fscanf(fp, " path for sigma %lg", &d)) == EOF)
FATAL("cmaes_resume_distribution(): 'path for sigma' not found",0,0,0);
else if (res==0)
fscanf(fp, " %*s");
else if(res > 0)
break;
}
/* read ps */
t->rgps[0] = d; res = 1;
for(i = 1; i < t->sp.N; ++i)
res += fscanf(fp, " %lg", &t->rgps[i]);
if (res != t->sp.N)
FATAL("cmaes_resume_distribution(): ps: dimensions differ",0,0,0);
/* find next "path for C" entry */
while (1) {
if ((res = fscanf(fp, " path for C %lg", &d)) == EOF)
FATAL("cmaes_resume_distribution(): 'path for C' not found",0,0,0);
else if (res==0)
fscanf(fp, " %*s");
else if(res > 0)
break;
}
/* read pc */
t->rgpc[0] = d; res = 1;
for(i = 1; i < t->sp.N; ++i)
res += fscanf(fp, " %lg", &t->rgpc[i]);
if (res != t->sp.N)
FATAL("cmaes_resume_distribution(): pc: dimensions differ",0,0,0);
/* find next "sigma" entry */
while (1) {
if ((res = fscanf(fp, " sigma %lg", &d)) == EOF)
FATAL("cmaes_resume_distribution(): 'sigma' not found",0,0,0);
else if (res==0)
fscanf(fp, " %*s");
else if(res > 0)
break;
}
t->sigma = d;
/* find next entry "covariance matrix" */
while (1) {
if ((res = fscanf(fp, " covariance matrix %lg", &d)) == EOF)
FATAL("cmaes_resume_distribution(): 'covariance matrix' not found",0,0,0);
else if (res==0)
fscanf(fp, " %*s");
else if(res > 0)
break;
}
/* read C */
t->C[0][0] = d; res = 1;
for (i = 1; i < t->sp.N; ++i)
for (j = 0; j <= i; ++j)
res += fscanf(fp, " %lg", &t->C[i][j]);
if (res != (t->sp.N*t->sp.N+t->sp.N)/2)
FATAL("cmaes_resume_distribution(): C: dimensions differ",0,0,0);
t->flgIniphase = 0;
t->flgEigensysIsUptodate = 0;
t->flgresumedone = 1;
cmaes_UpdateEigensystem(t, 1);
} /* cmaes_resume_distribution() */
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
void
cmaes_exit(cmaes_t *t)
{
int i, N = t->sp.N;
t->state = -1; /* not really useful at the moment */
free( t->rgpc);
free( t->rgps);
free( t->rgdTmp);
free( t->rgBDz);
free( --t->rgxmean);
free( --t->rgxold);
free( --t->rgxbestever);
free( --t->rgout);
free( t->rgD);
for (i = 0; i < N; ++i) {
free( t->C[i]);
free( t->B[i]);
}
for (i = 0; i < t->sp.lambda; ++i)
free( --t->rgrgx[i]);
free( t->rgrgx);
free( t->C);
free( t->B);
free( t->index);
free( t->publicFitness);
free( --t->rgFuncValue);
free( --t->arFuncValueHist);
random_exit (&t->rand);
readpara_exit (&t->sp);
} /* cmaes_exit() */
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
double const *
cmaes_SetMean(cmaes_t *t, const double *xmean)
/*
* Distribution mean could be changed before SamplePopulation().
* This might lead to unexpected behaviour if done repeatedly.
*/
{
int i, N=t->sp.N;
if (t->state >= 1 && t->state < 3)
FATAL("cmaes_SetMean: mean cannot be set inbetween the calls of ",
"SamplePopulation and UpdateDistribution",0,0);
if (xmean != NULL && xmean != t->rgxmean)
for(i = 0; i < N; ++i)
t->rgxmean[i] = xmean[i];
else
xmean = t->rgxmean;
return xmean;
}
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
double * const *
cmaes_SamplePopulation(cmaes_t *t)
{
int iNk, i, j, N=t->sp.N;
int flgdiag = ((t->sp.diagonalCov == 1) || (t->sp.diagonalCov >= t->gen));
double sum;
double const *xmean = t->rgxmean;
/* cmaes_SetMean(t, xmean); * xmean could be changed at this point */
/* calculate eigensystem */
if (!t->flgEigensysIsUptodate) {
if (!flgdiag)
cmaes_UpdateEigensystem(t, 0);
else {
for (i = 0; i < N; ++i)
t->rgD[i] = sqrt(t->C[i][i]);
t->minEW = douSquare(rgdouMin(t->rgD, N));
t->maxEW = douSquare(rgdouMax(t->rgD, N));
t->flgEigensysIsUptodate = 1;
timings_start(&t->eigenTimings);
}
}
/* treat minimal standard deviations and numeric problems */
TestMinStdDevs(t);
for (iNk = 0; iNk < t->sp.lambda; ++iNk)
{ /* generate scaled random vector (D * z) */
for (i = 0; i < N; ++i)
if (flgdiag)
t->rgrgx[iNk][i] = xmean[i] + t->sigma * t->rgD[i] * random_Gauss(&t->rand);
else
t->rgdTmp[i] = t->rgD[i] * random_Gauss(&t->rand);
if (!flgdiag)
/* add mutation (sigma * B * (D*z)) */
for (i = 0; i < N; ++i) {
for (j = 0, sum = 0.; j < N; ++j)
sum += t->B[i][j] * t->rgdTmp[j];
t->rgrgx[iNk][i] = xmean[i] + t->sigma * sum;
}
}
if(t->state == 3 || t->gen == 0)
++t->gen;
t->state = 1;
return(t->rgrgx);
} /* SamplePopulation() */
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
double const *
cmaes_ReSampleSingle_old( cmaes_t *t, double *rgx)
{
int i, j, N=t->sp.N;
double sum;
if (rgx == NULL)
FATAL("cmaes_ReSampleSingle(): Missing input double *x",0,0,0);
for (i = 0; i < N; ++i)
t->rgdTmp[i] = t->rgD[i] * random_Gauss(&t->rand);
/* add mutation (sigma * B * (D*z)) */
for (i = 0; i < N; ++i) {
for (j = 0, sum = 0.; j < N; ++j)
sum += t->B[i][j] * t->rgdTmp[j];
rgx[i] = t->rgxmean[i] + t->sigma * sum;
}
return rgx;
}
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
double * const *
cmaes_ReSampleSingle( cmaes_t *t, int index)
{
int i, j, N=t->sp.N;
double *rgx;
double sum;
static char s[99];
if (index < 0 || index >= t->sp.lambda) {
sprintf(s, "index==%d must be between 0 and %d", index, t->sp.lambda);
FATAL("cmaes_ReSampleSingle(): Population member ",s,0,0);
}
rgx = t->rgrgx[index];
for (i = 0; i < N; ++i)
t->rgdTmp[i] = t->rgD[i] * random_Gauss(&t->rand);
/* add mutation (sigma * B * (D*z)) */
for (i = 0; i < N; ++i) {
for (j = 0, sum = 0.; j < N; ++j)
sum += t->B[i][j] * t->rgdTmp[j];
rgx[i] = t->rgxmean[i] + t->sigma * sum;
}
return(t->rgrgx);
}
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
double *
cmaes_SampleSingleInto( cmaes_t *t, double *rgx)
{
int i, j, N=t->sp.N;
double sum;
if (rgx == NULL)
rgx = new_double(N);
for (i = 0; i < N; ++i)
t->rgdTmp[i] = t->rgD[i] * random_Gauss(&t->rand);
/* add mutation (sigma * B * (D*z)) */
for (i = 0; i < N; ++i) {
for (j = 0, sum = 0.; j < N; ++j)
sum += t->B[i][j] * t->rgdTmp[j];
rgx[i] = t->rgxmean[i] + t->sigma * sum;
}
return rgx;
}
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
double *
cmaes_PerturbSolutionInto( cmaes_t *t, double *rgx, double const *xmean, double eps)
{
int i, j, N=t->sp.N;
double sum;
if (rgx == NULL)
rgx = new_double(N);
if (xmean == NULL)
FATAL("cmaes_PerturbSolutionInto(): xmean was not given",0,0,0);
for (i = 0; i < N; ++i)
t->rgdTmp[i] = t->rgD[i] * random_Gauss(&t->rand);
/* add mutation (sigma * B * (D*z)) */
for (i = 0; i < N; ++i) {
for (j = 0, sum = 0.; j < N; ++j)
sum += t->B[i][j] * t->rgdTmp[j];
rgx[i] = xmean[i] + eps * t->sigma * sum;
}
return rgx;
}
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
double *
cmaes_UpdateDistribution( cmaes_t *t, const double *rgFunVal)
{
int i, j, iNk, hsig, N=t->sp.N;
int flgdiag = ((t->sp.diagonalCov == 1) || (t->sp.diagonalCov >= t->gen));
double sum;
double psxps;
if(t->state == 3)
FATAL("cmaes_UpdateDistribution(): You need to call \n",
"SamplePopulation() before update can take place.",0,0);
if(rgFunVal == NULL)
FATAL("cmaes_UpdateDistribution(): ",
"Fitness function value array input is missing.",0,0);
if(t->state == 1) /* function values are delivered here */
t->countevals += t->sp.lambda;
else
ERRORMESSAGE("cmaes_UpdateDistribution(): unexpected state",0,0,0);
/* assign function values */
for (i=0; i < t->sp.lambda; ++i)
t->rgrgx[i][N] = t->rgFuncValue[i] = rgFunVal[i];
/* Generate index */
Sorted_index(rgFunVal, t->index, t->sp.lambda);
/* Test if function values are identical, escape flat fitness */
if (t->rgFuncValue[t->index[0]] ==
t->rgFuncValue[t->index[(int)t->sp.lambda/2]]) {
t->sigma *= exp(0.2+t->sp.cs/t->sp.damps);
ERRORMESSAGE("Warning: sigma increased due to equal function values\n",
" Reconsider the formulation of the objective function",0,0);
}
/* update function value history */
for(i = (int)*(t->arFuncValueHist-1)-1; i > 0; --i) /* for(i = t->arFuncValueHist[-1]-1; i > 0; --i) */
t->arFuncValueHist[i] = t->arFuncValueHist[i-1];
t->arFuncValueHist[0] = rgFunVal[t->index[0]];
/* update xbestever */
if (t->rgxbestever[N] > t->rgrgx[t->index[0]][N] || t->gen == 1)
for (i = 0; i <= N; ++i) {
t->rgxbestever[i] = t->rgrgx[t->index[0]][i];
t->rgxbestever[N+1] = t->countevals;
}
/* calculate xmean and rgBDz~N(0,C) */
for (i = 0; i < N; ++i) {
t->rgxold[i] = t->rgxmean[i];
t->rgxmean[i] = 0.;
for (iNk = 0; iNk < t->sp.mu; ++iNk)
t->rgxmean[i] += t->sp.weights[iNk] * t->rgrgx[t->index[iNk]][i];
t->rgBDz[i] = sqrt(t->sp.mueff)*(t->rgxmean[i] - t->rgxold[i])/t->sigma;
}
/* calculate z := D^(-1) * B^(-1) * rgBDz into rgdTmp */
for (i = 0; i < N; ++i) {
if (!flgdiag)
for (j = 0, sum = 0.; j < N; ++j)
sum += t->B[j][i] * t->rgBDz[j];
else
sum = t->rgBDz[i];
t->rgdTmp[i] = sum / t->rgD[i];
}
/* TODO?: check length of t->rgdTmp and set an upper limit, e.g. 6 stds */
/* in case of manipulation of arx,
this can prevent an increase of sigma by several orders of magnitude
within one step; a five-fold increase in one step can still happen.
*/
/*
for (j = 0, sum = 0.; j < N; ++j)
sum += t->rgdTmp[j] * t->rgdTmp[j];
if (sqrt(sum) > chiN + 6. * sqrt(0.5)) {
rgdTmp length should be set to upper bound and hsig should become zero
}
*/
/* cumulation for sigma (ps) using B*z */
for (i = 0; i < N; ++i) {
if (!flgdiag)
for (j = 0, sum = 0.; j < N; ++j)
sum += t->B[i][j] * t->rgdTmp[j];
else
sum = t->rgdTmp[i];
t->rgps[i] = (1. - t->sp.cs) * t->rgps[i] +
sqrt(t->sp.cs * (2. - t->sp.cs)) * sum;
}
/* calculate norm(ps)^2 */
for (i = 0, psxps = 0.; i < N; ++i)
psxps += t->rgps[i] * t->rgps[i];
/* cumulation for covariance matrix (pc) using B*D*z~N(0,C) */
hsig = sqrt(psxps) / sqrt(1. - pow(1.-t->sp.cs, 2*t->gen)) / t->chiN
< 1.4 + 2./(N+1);
for (i = 0; i < N; ++i) {
t->rgpc[i] = (1. - t->sp.ccumcov) * t->rgpc[i] +
hsig * sqrt(t->sp.ccumcov * (2. - t->sp.ccumcov)) * t->rgBDz[i];
}
/* stop initial phase */
if (t->flgIniphase &&
t->gen > douMin(1/t->sp.cs, 1+N/t->sp.mucov))
{
if (psxps / t->sp.damps / (1.-pow((1. - t->sp.cs), t->gen))
< N * 1.05)
t->flgIniphase = 0;
}
#if 0
/* remove momentum in ps, if ps is large and fitness is getting worse */
/* This is obsolete due to hsig and harmful in a dynamic environment */
if(psxps/N > 1.5 + 10.*sqrt(2./N)
&& t->arFuncValueHist[0] > t->arFuncValueHist[1]
&& t->arFuncValueHist[0] > t->arFuncValueHist[2]) {
double tfac = sqrt((1 + douMax(0, log(psxps/N))) * N / psxps);
for (i=0; i<N; ++i)
t->rgps[i] *= tfac;
psxps *= tfac*tfac;
}
#endif
/* update of C */
Adapt_C2(t, hsig);
/* Adapt_C(t); not used anymore */
#if 0
if (t->sp.ccov != 0. && t->flgIniphase == 0) {
int k;
t->flgEigensysIsUptodate = 0;
/* update covariance matrix */
for (i = 0; i < N; ++i)
for (j = 0; j <=i; ++j) {
t->C[i][j] = (1 - t->sp.ccov) * t->C[i][j]
+ t->sp.ccov * (1./t->sp.mucov)
* (t->rgpc[i] * t->rgpc[j]
+ (1-hsig)*t->sp.ccumcov*(2.-t->sp.ccumcov) * t->C[i][j]);
for (k = 0; k < t->sp.mu; ++k) /* additional rank mu update */
t->C[i][j] += t->sp.ccov * (1-1./t->sp.mucov) * t->sp.weights[k]
* (t->rgrgx[t->index[k]][i] - t->rgxold[i])
* (t->rgrgx[t->index[k]][j] - t->rgxold[j])
/ t->sigma / t->sigma;
}
}
#endif
/* update of sigma */
t->sigma *= exp(((sqrt(psxps)/t->chiN)-1.)*t->sp.cs/t->sp.damps);
t->state = 3;
return (t->rgxmean);
} /* cmaes_UpdateDistribution() */
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
static void
Adapt_C2(cmaes_t *t, int hsig)
{
int i, j, k, N=t->sp.N;
int flgdiag = ((t->sp.diagonalCov == 1) || (t->sp.diagonalCov >= t->gen));
if (t->sp.ccov != 0. && t->flgIniphase == 0) {
/* definitions for speeding up inner-most loop */
double ccov1 = douMin(t->sp.ccov * (1./t->sp.mucov) * (flgdiag ? (N+1.5) / 3. : 1.), 1.);
double ccovmu = douMin(t->sp.ccov * (1-1./t->sp.mucov)* (flgdiag ? (N+1.5) / 3. : 1.), 1.-ccov1);
double sigmasquare = t->sigma * t->sigma;
t->flgEigensysIsUptodate = 0;
/* update covariance matrix */
for (i = 0; i < N; ++i)
for (j = flgdiag ? i : 0; j <= i; ++j) {
t->C[i][j] = (1 - ccov1 - ccovmu) * t->C[i][j]
+ ccov1
* (t->rgpc[i] * t->rgpc[j]
+ (1-hsig)*t->sp.ccumcov*(2.-t->sp.ccumcov) * t->C[i][j]);
for (k = 0; k < t->sp.mu; ++k) { /* additional rank mu update */
t->C[i][j] += ccovmu * t->sp.weights[k]
* (t->rgrgx[t->index[k]][i] - t->rgxold[i])
* (t->rgrgx[t->index[k]][j] - t->rgxold[j])
/ sigmasquare;
}
}
/* update maximal and minimal diagonal value */
t->maxdiagC = t->mindiagC = t->C[0][0];
for (i = 1; i < N; ++i) {
if (t->maxdiagC < t->C[i][i])
t->maxdiagC = t->C[i][i];
else if (t->mindiagC > t->C[i][i])
t->mindiagC = t->C[i][i];
}
} /* if ccov... */
}
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
static void
TestMinStdDevs(cmaes_t *t)
/* increases sigma */
{
int i, N = t->sp.N;
if (t->sp.rgDiffMinChange == NULL)
return;
for (i = 0; i < N; ++i)
while (t->sigma * sqrt(t->C[i][i]) < t->sp.rgDiffMinChange[i])
t->sigma *= exp(0.05+t->sp.cs/t->sp.damps);
} /* cmaes_TestMinStdDevs() */
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
void cmaes_WriteToFile(cmaes_t *t, const char *key, const char *name)
{
cmaes_WriteToFileAW(t, key, name, "a"); /* default is append */
}
/* --------------------------------------------------------- */
/* --------------------------------------------------------- */
void cmaes_WriteToFileAW(cmaes_t *t, const char *key, const char *name,
char *appendwrite)
{
char *s = "tmpcmaes.dat";
FILE *fp;
if (name == NULL)
name = s;
fp = fopen( name, appendwrite);
if(fp == NULL) {
ERRORMESSAGE("cmaes_WriteToFile(): could not open '", name,
"' with flag ", appendwrite);
return;
}
if (appendwrite[0] == 'w') {
/* write a header line, very rudimentary */
fprintf(fp, "%% # %s (randomSeed=%d, %s)\n", key, t->sp.seed, getTimeStr());
} else
if (t->gen > 0 || strncmp(name, "outcmaesfit", 11) != 0)
cmaes_WriteToFilePtr(t, key, fp); /* do not write fitness for gen==0 */
fclose(fp);
} /* WriteToFile */
/* --------------------------------------------------------- */
void cmaes_WriteToFilePtr(cmaes_t *t, const char *key, FILE *fp)
/* this hack reads key words from input key for data to be written to
* a file, see file signals.par as input file. The length of the keys
* is mostly fixed, see key += number in the code! If the key phrase
* does not match the expectation the output might be strange. for
* cmaes_t *t == NULL it solely prints key as a header line. Input key
* must be zero terminated.
*/
{
//printf("KEY = %s",key);
int i, k, N=(t ? t->sp.N : 0);
char const *keyend, *keystart;
char *s = "few";
if (key == NULL)
key = s;
keystart = key; /* for debugging purpose */
keyend = key + strlen(key);
while (key < keyend)
{
if (strncmp(key, "axisratio", 9) == 0)
{
fprintf(fp, "%.2e", sqrt(t->maxEW/t->minEW));
while (*key != '+' && *key != '\0' && key < keyend)
++key;
fprintf(fp, "%c", (*key=='+') ? '\t':'\n');
}
if (strncmp(key, "idxminSD", 8) == 0)
{
int mini=0; for(i=N-1;i>0;--i) if(t->mindiagC==t->C[i][i]) mini=i;
fprintf(fp, "%d", mini+1);
while (*key != '+' && *key != '\0' && key < keyend)
++key;
fprintf(fp, "%c", (*key=='+') ? '\t':'\n');
}
if (strncmp(key, "idxmaxSD", 8) == 0)
{
int maxi=0; for(i=N-1;i>0;--i) if(t->maxdiagC==t->C[i][i]) maxi=i;
fprintf(fp, "%d", maxi+1);
while (*key != '+' && *key != '\0' && key < keyend)
++key;
fprintf(fp, "%c", (*key=='+') ? '\t':'\n');
}
/* new coordinate system == all eigenvectors */
if (strncmp(key, "B", 1) == 0)
{
/* int j, index[N]; */
int j, *index=(int*)(new_void(N,sizeof(int))); /* MT */
Sorted_index(t->rgD, index, N); /* should not be necessary, see end of QLalgo2 */
/* One eigenvector per row, sorted: largest eigenvalue first */
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
fprintf(fp, "%g%c", t->B[j][index[N-1-i]], (j==N-1)?'\n':'\t');
++key;
free(index); /* MT */
}
/* covariance matrix */
if (strncmp(key, "C", 1) == 0)
{
int j;
for (i = 0; i < N; ++i)
for (j = 0; j <= i; ++j)
fprintf(fp, "%g%c", t->C[i][j], (j==i)?'\n':'\t');
++key;
}
/* (processor) time (used) since begin of execution */
if (strncmp(key, "clock", 4) == 0)
{
timings_update(&t->eigenTimings);
fprintf(fp, "%.1f %.1f", t->eigenTimings.totaltotaltime,
t->eigenTimings.tictoctime);
while (*key != '+' && *key != '\0' && key < keyend)
++key;
fprintf(fp, "%c", (*key=='+') ? '\t':'\n');
}
/* ratio between largest and smallest standard deviation */
if (strncmp(key, "stddevratio", 11) == 0) /* std dev in coordinate axes */