File: itkCMAEvolutionStrategyOptimizer.cxx

package info (click to toggle)
elastix 5.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 42,480 kB
  • sloc: cpp: 68,403; lisp: 4,118; python: 1,013; xml: 182; sh: 177; makefile: 33
file content (1163 lines) | stat: -rw-r--r-- 36,550 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
/*=========================================================================
 *
 *  Copyright UMC Utrecht and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkCMAEvolutionStrategyOptimizer.h"
#include "itkSymmetricEigenAnalysis.h"
#include <vnl/vnl_math.h>
#include <algorithm>
#include <cmath>
#include "itkCommand.h"
#include "itkEventObject.h"
#include "itkMacro.h"

namespace itk
{

/**
 * ******************** Constructor *************************
 */

CMAEvolutionStrategyOptimizer::CMAEvolutionStrategyOptimizer()
{
  itkDebugMacro("Constructor");

} // end constructor


/**
 * ******************* PrintSelf *********************
 */

void
CMAEvolutionStrategyOptimizer::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  // os << indent << "m_RandomGenerator: " << this->m_RandomGenerator << std::endl;
  os << indent << "m_CurrentValue: " << this->m_CurrentValue << std::endl;
  os << indent << "m_CurrentIteration: " << this->m_CurrentIteration << std::endl;
  os << indent << "m_StopCondition: " << this->m_StopCondition << std::endl;
  os << indent << "m_Stop: " << this->m_Stop << std::endl;

  os << indent << "m_UseCovarianceMatrixAdaptation: " << this->m_UseCovarianceMatrixAdaptation << std::endl;
  os << indent << "m_PopulationSize: " << this->m_PopulationSize << std::endl;
  os << indent << "m_NumberOfParents: " << this->m_NumberOfParents << std::endl;
  os << indent << "m_UpdateBDPeriod: " << this->m_UpdateBDPeriod << std::endl;

  os << indent << "m_EffectiveMu: " << this->m_EffectiveMu << std::endl;
  os << indent << "m_ConjugateEvolutionPathConstant: " << this->m_ConjugateEvolutionPathConstant << std::endl;
  os << indent << "m_SigmaDampingConstant: " << this->m_SigmaDampingConstant << std::endl;
  os << indent << "m_CovarianceMatrixAdaptationConstant: " << this->m_CovarianceMatrixAdaptationConstant << std::endl;
  os << indent << "m_EvolutionPathConstant: " << this->m_EvolutionPathConstant << std::endl;
  os << indent << "m_CovarianceMatrixAdaptationWeight: " << this->m_CovarianceMatrixAdaptationWeight << std::endl;
  os << indent << "m_ExpectationNormNormalDistribution: " << this->m_ExpectationNormNormalDistribution << std::endl;
  os << indent << "m_HistoryLength: " << this->m_HistoryLength << std::endl;

  os << indent << "m_CurrentSigma: " << this->m_CurrentSigma << std::endl;
  os << indent << "m_Heaviside: " << this->m_Heaviside << std::endl;
  os << indent << "m_CurrentMaximumD: " << this->m_CurrentMaximumD << std::endl;
  os << indent << "m_CurrentMinimumD: " << this->m_CurrentMinimumD << std::endl;

  os << indent << "m_MaximumNumberOfIterations: " << this->m_MaximumNumberOfIterations << std::endl;
  os << indent << "m_UseDecayingSigma: " << this->m_UseDecayingSigma << std::endl;
  os << indent << "m_InitialSigma: " << this->m_InitialSigma << std::endl;
  os << indent << "m_SigmaDecayA: " << this->m_SigmaDecayA << std::endl;
  os << indent << "m_SigmaDecayAlpha: " << this->m_SigmaDecayAlpha << std::endl;
  os << indent << "m_RecombinationWeightsPreset: " << this->m_RecombinationWeightsPreset << std::endl;
  os << indent << "m_MaximumDeviation: " << this->m_MaximumDeviation << std::endl;
  os << indent << "m_MinimumDeviation: " << this->m_MinimumDeviation << std::endl;
  os << indent << "m_PositionToleranceMin: " << this->m_PositionToleranceMin << std::endl;
  os << indent << "m_PositionToleranceMax: " << this->m_PositionToleranceMax << std::endl;
  os << indent << "m_ValueTolerance: " << this->m_ValueTolerance << std::endl;

  os << indent << "m_RecombinationWeights: " << this->m_RecombinationWeights << std::endl;
  os << indent << "m_C: " << this->m_C << std::endl;
  os << indent << "m_B: " << this->m_B << std::endl;
  os << indent << "m_D: " << this->m_D.diagonal() << std::endl;

  // template:
  // os << indent << ": " << this-> << std::endl;

} // end PrintSelf;


/**
 * ******************* StartOptimization *********************
 */

void
CMAEvolutionStrategyOptimizer::StartOptimization()
{
  itkDebugMacro("StartOptimization");

  /** Reset some variables */
  this->m_CurrentValue = MeasureType{};
  this->m_CurrentIteration = 0;
  this->m_Stop = false;
  this->m_StopCondition = Unknown;

  /** Get the number of parameters; checks also if a cost function has been set at all.
   * if not: an exception is thrown */
  this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Initialize the scaledCostFunction with the currently set scales */
  this->InitializeScales();

  /** Set the current position as the scaled initial position */
  this->SetCurrentPosition(this->GetInitialPosition());

  /** Compute default values for a lot of constants */
  this->InitializeConstants();

  /** Resize/Initialize variables used that are updated during optimisation */
  this->InitializeProgressVariables();

  /** Resize/Initialize B, C, and D */
  this->InitializeBCD();

  if (!this->m_Stop)
  {
    this->ResumeOptimization();
  }

} // end StartOptimization


/**
 * ******************* ResumeOptimization *********************
 */

void
CMAEvolutionStrategyOptimizer::ResumeOptimization()
{
  itkDebugMacro("ResumeOptimization");

  this->m_StopCondition = Unknown;

  this->InvokeEvent(StartEvent());

  try
  {
    this->m_CurrentValue = this->GetScaledValue(this->GetScaledCurrentPosition());
  }
  catch (const ExceptionObject &)
  {
    this->m_StopCondition = MetricError;
    this->StopOptimization();
    throw;
  }

  /** Test if not by chance we are already converged */
  bool convergence = this->TestConvergence(true);
  if (convergence)
  {
    this->StopOptimization();
  }

  /** Start iterating */
  while (!this->m_Stop)
  {
    this->GenerateOffspring();
    this->SortCostFunctionValues();

    /** Something may have gone wrong during evaluation of the cost function values */
    if (this->m_Stop)
    {
      break;
    }

    this->AdvanceOneStep();

    /** Something may have gone wrong during evalution of the current value */
    if (this->m_Stop)
    {
      break;
    }

    /** Give the user opportunity to observe progress (current value/position/sigma etc.) */
    this->InvokeEvent(IterationEvent());

    if (this->m_Stop)
    {
      break;
    }

    /** Prepare for next iteration */
    this->UpdateConjugateEvolutionPath();
    this->UpdateHeaviside();
    this->UpdateEvolutionPath();
    this->UpdateC();
    this->UpdateSigma();
    this->UpdateBD();
    this->FixNumericalErrors();

    /** Test if convergence has occurred in some sense */
    convergence = this->TestConvergence(false);
    if (convergence)
    {
      this->StopOptimization();
      break;
    }

    /** Next iteration */
    ++(this->m_CurrentIteration);

  } // end while !m_Stop

} // end ResumeOptimization


/**
 * *********************** StopOptimization *****************************
 */

void
CMAEvolutionStrategyOptimizer::StopOptimization()
{
  itkDebugMacro("StopOptimization");
  this->m_Stop = true;
  this->InvokeEvent(EndEvent());
} // end StopOptimization()


/**
 * ****************** InitializeConstants *********************
 */

void
CMAEvolutionStrategyOptimizer::InitializeConstants()
{
  itkDebugMacro("InitializeConstants");

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** m_PopulationSize (if not provided by the user) */
  if (this->m_PopulationSize == 0)
  {
    this->m_PopulationSize =
      4 + static_cast<unsigned int>(std::floor(3.0 * std::log(static_cast<double>(numberOfParameters))));
  }

  /** m_NumberOfParents (if not provided by the user) */
  if (this->m_NumberOfParents == 0)
  {
    this->m_NumberOfParents = this->m_PopulationSize / 2;
  }

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;
  const double       Nd = static_cast<double>(N);
  const unsigned int lambda = this->m_PopulationSize;
  const double       lambdad = static_cast<double>(lambda);
  const unsigned int mu = this->m_NumberOfParents;
  const double       mud = static_cast<double>(mu);

  /** m_RecombinationWeights */
  this->m_RecombinationWeights.SetSize(mu);
  this->m_RecombinationWeights.Fill(1.0); // "equal" preset
  if (this->m_RecombinationWeightsPreset == "linear")
  {
    for (unsigned int i = 0; i < mu; ++i)
    {
      this->m_RecombinationWeights[i] = mud + 1.0 - static_cast<double>(i + 1);
    }
  }
  else if (this->m_RecombinationWeightsPreset == "superlinear")
  {
    const double logmud = std::log(mud + 1.0);
    for (unsigned int i = 0; i < mu; ++i)
    {
      this->m_RecombinationWeights[i] = logmud - std::log(static_cast<double>(i + 1));
    }
  }
  this->m_RecombinationWeights /= this->m_RecombinationWeights.sum();

  /** m_EffectiveMu */
  this->m_EffectiveMu = 1.0 / this->m_RecombinationWeights.squared_magnitude();
  if (this->m_EffectiveMu >= lambdad)
  {
    itkExceptionMacro("The RecombinationWeights have unreasonable values!");
  }
  /** alias: */
  const double mueff = this->m_EffectiveMu;

  /** m_ConjugateEvolutionPathConstant (c_\sigma) */
  this->m_ConjugateEvolutionPathConstant = (mueff + 2.0) / (Nd + mueff + 3.0);

  /** m_SigmaDampingConstant */
  this->m_SigmaDampingConstant = this->m_ConjugateEvolutionPathConstant +
                                 (1.0 + 2.0 * std::max(0.0, std::sqrt((mueff - 1.0) / (Nd + 1.0)) - 1.0)) *
                                   std::max(0.3, 1.0 - Nd / static_cast<double>(this->m_MaximumNumberOfIterations));

  /** m_CovarianceMatrixAdaptationWeight (\mu_cov)*/
  this->m_CovarianceMatrixAdaptationWeight = mueff;
  /** alias: */
  const double mucov = this->m_CovarianceMatrixAdaptationWeight;

  /** m_CovarianceMatrixAdaptationConstant (c_cov) */
  this->m_CovarianceMatrixAdaptationConstant =
    (1.0 / mucov) * 2.0 / vnl_math::sqr(Nd + std::sqrt(2.0)) +
    (1.0 - 1.0 / mucov) * std::min(1.0, (2.0 * mueff - 1.0) / (vnl_math::sqr(Nd + 2.0) + mueff));
  /** alias: */
  const double c_cov = this->m_CovarianceMatrixAdaptationConstant;

  /** Update only every 'period' iterations */
  if (this->m_UpdateBDPeriod == 0)
  {
    this->m_UpdateBDPeriod = static_cast<unsigned int>(std::floor(1.0 / c_cov / Nd / 10.0));
  }
  this->m_UpdateBDPeriod = std::max(static_cast<unsigned int>(1), this->m_UpdateBDPeriod);
  if (this->m_UpdateBDPeriod >= this->m_MaximumNumberOfIterations)
  {
    this->SetUseCovarianceMatrixAdaptation(false);
  }

  /** m_EvolutionPathConstant (c_c)*/
  this->m_EvolutionPathConstant = 4.0 / (Nd + 4.0);

  /** m_ExpectationNormNormalDistribution */
  this->m_ExpectationNormNormalDistribution =
    std::sqrt(Nd) * (1.0 - 1.0 / (4.0 * Nd) + 1.0 / (21.0 * vnl_math::sqr(Nd)));

  /** m_HistoryLength */
  this->m_HistoryLength = static_cast<unsigned long>(std::min(
    this->GetMaximumNumberOfIterations(), 10 + static_cast<unsigned long>(std::ceil(3.0 * 10.0 * Nd / lambdad))));

} // end InitializeConstants


/**
 * ****************** InitializeProgressVariables *********************
 */

void
CMAEvolutionStrategyOptimizer::InitializeProgressVariables()
{
  itkDebugMacro("InitializeProgressVariables");

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;
  const unsigned int lambda = this->m_PopulationSize;

  /** CurrentSigma */
  this->m_CurrentSigma = this->GetInitialSigma();

  /** Heaviside */
  this->m_Heaviside = 0.0;

  /** m_SearchDirs */
  const ParametersType zeroParam(N, 0.0);
  this->m_SearchDirs.clear();
  this->m_SearchDirs.resize(lambda, zeroParam);

  /** m_NormalizedSearchDirs */
  this->m_NormalizedSearchDirs.clear();
  this->m_NormalizedSearchDirs.resize(lambda, zeroParam);

  /** m_CostFunctionValues */
  this->m_CostFunctionValues.clear();

  /** m_CurrentScaledStep */
  this->m_CurrentScaledStep.SetSize(N);
  this->m_CurrentScaledStep.Fill(0.0);

  /** m_CurrentNormalizedStep */
  this->m_CurrentNormalizedStep.SetSize(N);
  this->m_CurrentNormalizedStep.Fill(0.0);

  /** m_EvolutionPath */
  this->m_EvolutionPath.SetSize(N);
  this->m_EvolutionPath.Fill(0.0);

  /** m_ConjugateEvolutionPath */
  this->m_ConjugateEvolutionPath.SetSize(N);
  this->m_ConjugateEvolutionPath.Fill(0.0);

  /** m_MeasureHistory */
  this->m_MeasureHistory.clear();

  /** Maximum and minimum square root eigenvalues */
  this->m_CurrentMaximumD = 1.0;
  this->m_CurrentMinimumD = 1.0;

} // end InitializeProgressVariables


/**
 * ****************** InitializeBCD *********************
 */

void
CMAEvolutionStrategyOptimizer::InitializeBCD()
{
  itkDebugMacro("InitializeBCD");

  if (this->GetUseCovarianceMatrixAdaptation())
  {
    /** Get the number of parameters from the cost function */
    const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

    /** Some casts/aliases: */
    const unsigned int N = numberOfParameters;

    /** Resize */
    this->m_B.set_size(N, N);
    this->m_C.set_size(N, N);
    this->m_D.set_size(N);

    /** Initialize */
    this->m_B.fill(0.0);
    this->m_C.fill(0.0);
    this->m_B.fill_diagonal(1.0);
    this->m_C.fill_diagonal(1.0);
    this->m_D.fill(1.0);
  }
  else
  {
    /** Clear */
    this->m_B.set_size(0, 0);
    this->m_C.set_size(0, 0);
    this->m_D.clear();
  }

} // end InitializeBCD


/**
 * ****************** GenerateOffspring *********************
 */

void
CMAEvolutionStrategyOptimizer::GenerateOffspring()
{
  itkDebugMacro("GenerateOffspring");

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;
  const unsigned int lambda = this->m_PopulationSize;

  /** Clear the old values */
  this->m_CostFunctionValues.clear();

  /** Fill the m_NormalizedSearchDirs and SearchDirs */
  unsigned int lam = 0;
  unsigned int nrOfFails = 0;
  while (lam < lambda)
  {
    /** draw from distribution N(0,I) */
    for (unsigned int par = 0; par < N; ++par)
    {
      this->m_NormalizedSearchDirs[lam][par] = this->m_RandomGenerator->GetNormalVariate();
    }
    /** Make like it was drawn from N(0,C) */
    if (this->GetUseCovarianceMatrixAdaptation())
    {
      this->m_SearchDirs[lam] = this->m_B * (this->m_D * this->m_NormalizedSearchDirs[lam]);
    }
    else
    {
      this->m_SearchDirs[lam] = this->m_NormalizedSearchDirs[lam];
    }
    /** Make like it was drawn from N( 0, sigma^2 C ) */
    this->m_SearchDirs[lam] *= this->m_CurrentSigma;

    /** Compute the cost function */
    MeasureType costFunctionValue = 0.0;
    /** x_lam = m + d_lam */
    ParametersType x_lam = this->GetScaledCurrentPosition();
    x_lam += this->m_SearchDirs[lam];
    try
    {
      costFunctionValue = this->GetScaledValue(x_lam);
    }
    catch (const ExceptionObject &)
    {
      ++nrOfFails;
      /** try another parameter vector if we haven't tried that for 10 times already */
      if (nrOfFails <= 10)
      {
        continue;
      }
      else
      {
        this->m_StopCondition = MetricError;
        this->StopOptimization();
        throw;
      }
    }
    /** Successfull cost function evaluation */
    this->m_CostFunctionValues.push_back(MeasureIndexPairType(costFunctionValue, lam));

    /** Reset the number of failed cost function evaluations */
    nrOfFails = 0;

    /** next offspring member */
    ++lam;
  }

} // end GenerateOffspring


/**
 * ****************** SortCostFunctionValues *********************
 */

void
CMAEvolutionStrategyOptimizer::SortCostFunctionValues()
{
  itkDebugMacro("SortCostFunctionValues");

  /** Sort the cost function values in order of increasing cost function value */
  std::sort(this->m_CostFunctionValues.begin(), this->m_CostFunctionValues.end());

  /** Store the best value in the history, and remove the oldest entry of the
   * the history if the history exceeds the HistoryLength */
  this->m_MeasureHistory.push_front(this->m_CostFunctionValues[0].first);
  if (this->m_MeasureHistory.size() > this->m_HistoryLength)
  {
    this->m_MeasureHistory.pop_back();
  }

} // end SortCostFunctionValues


/**
 * ****************** AdvanceOneStep *********************
 */

void
CMAEvolutionStrategyOptimizer::AdvanceOneStep()
{
  itkDebugMacro("AdvanceOneStep");

  /** Some casts/aliases: */
  const unsigned int mu = this->m_NumberOfParents;

  /** Compute the CurrentScaledStep, using the RecombinationWeights and
   * the sorted CostFunctionValues-vector.
   * On the fly, also compute the CurrentNormalizedStep */
  this->m_CurrentScaledStep.Fill(0.0);
  this->m_CurrentNormalizedStep.Fill(0.0);
  for (unsigned int m = 0; m < mu; ++m)
  {
    const unsigned int lam = this->m_CostFunctionValues[m].second;
    const double       weight = this->m_RecombinationWeights[m];
    this->m_CurrentScaledStep += (weight * this->m_SearchDirs[lam]);
    this->m_CurrentNormalizedStep += (weight * this->m_NormalizedSearchDirs[lam]);
  }

  /** Set the new current position */
  ParametersType newPos = this->GetScaledCurrentPosition();
  newPos += this->GetCurrentScaledStep();
  this->SetScaledCurrentPosition(newPos);

  /** Compute the cost function at the new position */
  try
  {
    this->m_CurrentValue = this->GetScaledValue(this->GetScaledCurrentPosition());
  }
  catch (const ExceptionObject &)
  {
    this->m_StopCondition = MetricError;
    this->StopOptimization();
    throw;
  }
} // end AdvanceOneStep


/**
 * ****************** UpdateConjugateEvolutionPath *********************
 */

void
CMAEvolutionStrategyOptimizer::UpdateConjugateEvolutionPath()
{
  itkDebugMacro("UpdateConjugateEvolutionPath");

  /** Some casts/aliases: */
  const double c_sigma = this->m_ConjugateEvolutionPathConstant;

  /** Update p_sigma */
  const double factor = std::sqrt(c_sigma * (2.0 - c_sigma) * this->m_EffectiveMu);
  this->m_ConjugateEvolutionPath *= (1.0 - c_sigma);
  if (this->GetUseCovarianceMatrixAdaptation())
  {
    this->m_ConjugateEvolutionPath += (factor * (this->m_B * this->m_CurrentNormalizedStep));
  }
  else
  {
    this->m_ConjugateEvolutionPath += (factor * this->m_CurrentNormalizedStep);
  }

} // end UpdateConjugateEvolutionPath


/**
 * ****************** UpdateHeaviside *********************
 */

void
CMAEvolutionStrategyOptimizer::UpdateHeaviside()
{
  itkDebugMacro("UpdateHeaviside");

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;
  const double       Nd = static_cast<double>(N);
  const double       c_sigma = this->m_ConjugateEvolutionPathConstant;
  const int          nextit = static_cast<int>(this->GetCurrentIteration() + 1);
  const double       chiN = this->m_ExpectationNormNormalDistribution;

  /** Compute the Heaviside function: */
  this->m_Heaviside = false;
  const double normps = this->m_ConjugateEvolutionPath.magnitude();
  const double denom = std::sqrt(1.0 - std::pow(1.0 - c_sigma, 2 * nextit));
  const double righthandside = 1.5 + 1.0 / (Nd - 0.5);
  if ((normps / denom / chiN) < righthandside)
  {
    this->m_Heaviside = true;
  }

} // end UpdateHeaviside


/**
 * ****************** UpdateEvolutionPath *********************
 */

void
CMAEvolutionStrategyOptimizer::UpdateEvolutionPath()
{
  itkDebugMacro("UpdateEvolutionPath");

  /** Some casts/aliases: */
  const double c_c = this->m_EvolutionPathConstant;

  /** Compute the evolution path p_c */
  this->m_EvolutionPath *= (1.0 - c_c);
  if (this->m_Heaviside)
  {
    const double factor = std::sqrt(c_c * (2.0 - c_c) * this->m_EffectiveMu) / this->m_CurrentSigma;
    this->m_EvolutionPath += (factor * this->m_CurrentScaledStep);
  }

} // end UpdateEvolutionPath


/**
 * ****************** UpdateC *********************
 */

void
CMAEvolutionStrategyOptimizer::UpdateC()
{
  itkDebugMacro("UpdateC");

  if (!(this->GetUseCovarianceMatrixAdaptation()))
  {
    /** We don't need C */
    return;
  }

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;
  const unsigned int mu = this->m_NumberOfParents;
  const double       c_c = this->m_EvolutionPathConstant;
  const double       c_cov = this->m_CovarianceMatrixAdaptationConstant;
  const double       mu_cov = this->m_CovarianceMatrixAdaptationWeight;
  const double       sigma = this->m_CurrentSigma;

  /** Multiply old m_C with some factor */
  double oldCfactor = 1.0 - c_cov;
  if (!this->m_Heaviside)
  {
    oldCfactor += (c_cov * c_c * (2.0 - c_c) / mu_cov);
  }
  this->m_C *= oldCfactor;

  /** Do rank-one update */
  const double rankonefactor = c_cov / mu_cov;
  for (unsigned int i = 0; i < N; ++i)
  {
    const double evolutionPath_i = this->m_EvolutionPath[i];
    for (unsigned int j = 0; j < N; ++j)
    {
      const double update = rankonefactor * evolutionPath_i * this->m_EvolutionPath[j];
      this->m_C[i][j] += update;
    }
  }

  /** Do rank-mu update */
  const double rankmufactor = c_cov * (1.0 - 1.0 / mu_cov);
  for (unsigned int m = 0; m < mu; ++m)
  {
    const unsigned int lam = this->m_CostFunctionValues[m].second;
    const double       sqrtweight = std::sqrt(this->m_RecombinationWeights[m]);
    ParametersType     weightedSearchDir = this->m_SearchDirs[lam];
    weightedSearchDir *= (sqrtweight / sigma);
    for (unsigned int i = 0; i < N; ++i)
    {
      const double weightedSearchDir_i = weightedSearchDir[i];
      for (unsigned int j = 0; j < N; ++j)
      {
        const double update = rankmufactor * weightedSearchDir_i * weightedSearchDir[j];
        this->m_C[i][j] += update;
      }
    }
  } // end for m

} // end UpdateC


/**
 * ****************** UpdateSigma *********************
 */

void
CMAEvolutionStrategyOptimizer::UpdateSigma()
{
  itkDebugMacro("UpdateSigma");

  if (this->GetUseDecayingSigma())
  {
    const double it = static_cast<double>(this->GetCurrentIteration());
    const double num = std::pow(this->m_SigmaDecayA + it, this->m_SigmaDecayAlpha);
    const double den = std::pow(this->m_SigmaDecayA + it + 1.0, this->m_SigmaDecayAlpha);
    this->m_CurrentSigma *= num / den;
  }
  else
  {
    const double normps = this->m_ConjugateEvolutionPath.magnitude();
    const double chiN = this->m_ExpectationNormNormalDistribution;
    const double c_sigma = this->m_ConjugateEvolutionPathConstant;
    const double d_sigma = this->m_SigmaDampingConstant;
    this->m_CurrentSigma *= std::exp((normps / chiN - 1.0) * c_sigma / d_sigma);
  }

} // end UpdateSigma


/**
 * ****************** UpdateBD *********************
 */

void
CMAEvolutionStrategyOptimizer::UpdateBD()
{
  itkDebugMacro("UpdateBD");

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;
  const int          nextit = static_cast<int>(this->GetCurrentIteration() + 1);

  /** Update only every 'm_UpdateBDPeriod' iterations */
  unsigned int periodover = nextit % this->m_UpdateBDPeriod;

  if (!(this->GetUseCovarianceMatrixAdaptation()) || (periodover != 0))
  {
    /** We don't need to update B and D */
    return;
  }

  using EigenAnalysisType =
    itk::SymmetricEigenAnalysis<CovarianceMatrixType, EigenValueMatrixType, CovarianceMatrixType>;

  /** In the itkEigenAnalysis only the upper triangle of the matrix will be accessed, so
   * we do not need to make sure the matrix is symmetric, like in the
   * matlab code. Just run the eigenAnalysis! */
  EigenAnalysisType eigenAnalysis(N);
  unsigned int      returncode = 0;
  returncode = eigenAnalysis.ComputeEigenValuesAndVectors(this->m_C, this->m_D, this->m_B);
  if (returncode != 0)
  {
    itkExceptionMacro("EigenAnalysis failed while computing eigenvalue nr: " << returncode);
  }

  /** itk eigen analysis returns eigen vectors in rows... */
  this->m_B.inplace_transpose();

  /**  limit condition of C to 1e10 + 1, and avoid negative eigenvalues */
  const double largeNumber = 1e10;
  double       dmax = this->m_D.diagonal().max_value();
  double       dmin = this->m_D.diagonal().min_value();
  if (dmin < 0.0)
  {
    const double diagadd = dmax / largeNumber;
    for (unsigned int i = 0; i < N; ++i)
    {
      if (this->m_D[i] < 0.0)
      {
        this->m_D[i] = 0.0;
      }
      this->m_C[i][i] += diagadd;
      this->m_D[i] += diagadd;
    }
  }

  dmax = this->m_D.diagonal().max_value();
  dmin = this->m_D.diagonal().min_value();
  if (dmax > dmin * largeNumber)
  {
    const double diagadd = dmax / largeNumber - dmin;
    for (unsigned int i = 0; i < N; ++i)
    {
      this->m_C[i][i] += diagadd;
      this->m_D[i] += diagadd;
    }
  }

  /** the D matrix is supposed to contain the square root of the eigen values */
  for (unsigned int i = 0; i < N; ++i)
  {
    this->m_D[i] = std::sqrt(this->m_D[i]);
  }

  /** Keep for the user */
  this->m_CurrentMaximumD = this->m_D.diagonal().max_value();
  this->m_CurrentMinimumD = this->m_D.diagonal().min_value();

} // end UpdateBD


/**
 * **************** FixNumericalErrors ********************
 */

void
CMAEvolutionStrategyOptimizer::FixNumericalErrors()
{
  itkDebugMacro("FixNumericalErrors");

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;
  const double       c_sigma = this->m_ConjugateEvolutionPathConstant;
  const double       c_cov = this->m_CovarianceMatrixAdaptationConstant;
  const double       d_sigma = this->m_SigmaDampingConstant;
  const double       strange_factor = std::exp(0.05 + c_sigma / d_sigma);
  const double       strange_factor2 = std::exp(0.2 + c_sigma / d_sigma);
  const unsigned int nextit = this->m_CurrentIteration + 1;

  /** Check if m_MaximumDeviation and m_MinimumDeviation are satisfied. This
   * check is different depending on the m_UseCovarianceMatrixAdaptation flag */
  if (this->GetUseCovarianceMatrixAdaptation())
  {
    /** Check for too large deviation */
    for (unsigned int i = 0; i < N; ++i)
    {
      const double sqrtCii = std::sqrt(this->m_C[i][i]);
      const double actualDev = this->m_CurrentSigma * sqrtCii;
      if (actualDev > this->m_MaximumDeviation)
      {
        this->m_CurrentSigma = this->m_MaximumDeviation / sqrtCii;
      }
    }

    /** Check for too small deviation */
    bool minDevViolated = false;
    for (unsigned int i = 0; i < N; ++i)
    {
      const double sqrtCii = std::sqrt(this->m_C[i][i]);
      const double actualDev = this->m_CurrentSigma * sqrtCii;
      if (actualDev < this->m_MinimumDeviation)
      {
        this->m_CurrentSigma = this->m_MinimumDeviation / sqrtCii;
        minDevViolated = true;
      }
    }
    if (minDevViolated)
    {
      /** \todo: does this make sense if m_UseDecayingSigma == true??
       * Anyway, we have to do something, in order to satisfy the minimum deviation */
      this->m_CurrentSigma *= strange_factor;
    }
  }
  else
  {
    /** If no covariance matrix adaptation is used, the check becomes simpler */

    /** Check for too large deviation */
    double actualDev = this->m_CurrentSigma;
    if (actualDev > this->m_MaximumDeviation)
    {
      this->m_CurrentSigma = this->m_MaximumDeviation;
    }
    /** Check for too small deviation */
    bool minDevViolated = false;
    actualDev = this->m_CurrentSigma;
    if (actualDev < this->m_MinimumDeviation)
    {
      this->m_CurrentSigma = this->m_MinimumDeviation;
      minDevViolated = true;
    }
    if (minDevViolated)
    {
      /** \todo: does this make sense if m_UseDecayingSigma == true??
       * Anyway, we have to do something, in order to satisfy the minimum deviation */
      this->m_CurrentSigma *= strange_factor;
    }

  } // end else: no covariance matrix adaptation

  /** Adjust too low coordinate axis deviations that would cause numerical
   * problems (because of finite precision of the datatypes). This check
   * is different depending on the m_UseCovarianceMatrixAdaptation flag */
  const ParametersType & param = this->GetScaledCurrentPosition();
  bool                   numericalProblemsEncountered = false;
  if (this->GetUseCovarianceMatrixAdaptation())
  {
    /** Check for numerically too small deviation */
    for (unsigned int i = 0; i < N; ++i)
    {
      const double actualDev = 0.2 * this->m_CurrentSigma * std::sqrt(this->m_C[i][i]);
      if (param[i] == (param[i] + actualDev))
      {
        /** The parameters wouldn't change after perturbation, because
         * of too low precision. Increase the problematic diagonal element of C */
        this->m_C[i][i] *= (1.0 + c_cov);
        numericalProblemsEncountered = true;
      }
    } // end for i
  }
  else
  {
    const double actualDev = 0.2 * this->m_CurrentSigma;
    for (unsigned int i = 0; i < N; ++i)
    {
      if (param[i] == (param[i] + actualDev))
      {
        /** The parameters wouldn't change after perturbation, because
         * of too low precision. Increase the sigma (equivalent to
         * increasing a diagonal element of C^0.5).  */
        this->m_CurrentSigma *= std::sqrt(1.0 + c_cov);
        numericalProblemsEncountered = true;
      }
    }
  } // end else: no covariance matrix adaptation
  if (numericalProblemsEncountered)
  {
    /** \todo: does this make sense if m_UseDecayingSigma == true??
     * Anyway, we have to do something, in order to solve the numerical problems */
    this->m_CurrentSigma *= strange_factor;
  }

  /** Check if "main axis standard deviation sigma*D(i,i) has effect" (?),
   * with i = 1+floor(mod(countiter,N))
   * matlabcode: if all( xmean == xmean + 0.1*sigma*B*D(:,i) )
   * B*D(:,i) = i'th column of B times eigenvalue = i'th eigenvector * eigenvalue[i]
   * In the code below: colnr=i-1 (zero-based indexing). */
  bool               numericalProblemsEncountered2 = false;
  const unsigned int colnr = static_cast<unsigned int>(nextit % N);
  if (this->GetUseCovarianceMatrixAdaptation())
  {
    const double sigDcol = 0.1 * this->m_CurrentSigma * this->m_D[colnr];
    // const ParametersType actualDevVector = sigDcol * this->m_B.get_column(colnr);
    const ParametersType::VnlVectorType actualDevVector = sigDcol * this->m_B.get_column(colnr);
    if (param == (param + actualDevVector))
    {
      numericalProblemsEncountered2 = true;
    }
  }
  else
  {
    /** B and D are not used, so can be considered identity matrices.
     * This simplifies the check */
    const double sigDcol = 0.1 * this->m_CurrentSigma;
    if (param[colnr] == (param[colnr] + sigDcol))
    {
      numericalProblemsEncountered2 = true;
    }
  } // end else: no covariance matrix adaptation
  if (numericalProblemsEncountered2)
  {
    /** \todo: does this make sense if m_UseDecayingSigma == true??
     * Anyway, we have to do something, in order to solve the numerical problems */
    this->m_CurrentSigma *= strange_factor2;
  }

  /** Adjust step size in case of equal function values (flat fitness) */

  /** The indices of the two population members whose cost function will
   * be compared */
  const unsigned int populationMemberA = 0;
  const unsigned int populationMemberB =
    static_cast<unsigned int>(std::ceil(0.1 + static_cast<double>(this->m_PopulationSize) / 4.0));
  /** If they are the same: increase sigma with a magic factor */
  if (this->m_CostFunctionValues[populationMemberA].first == this->m_CostFunctionValues[populationMemberB].first)
  {
    this->m_CurrentSigma *= strange_factor2;
  }

  /** Check if the best function value changes over iterations */
  if (this->m_MeasureHistory.size() > 1)
  {
    const MeasureType maxhist = *max_element(this->m_MeasureHistory.begin(), this->m_MeasureHistory.end());
    const MeasureType minhist = *min_element(this->m_MeasureHistory.begin(), this->m_MeasureHistory.end());
    if (maxhist == minhist)
    {
      this->m_CurrentSigma *= strange_factor2;
    }
  }

} // end FixNumericalErrors


/**
 * ********************* TestConvergence ************************
 */

bool
CMAEvolutionStrategyOptimizer::TestConvergence(bool firstCheck)
{
  itkDebugMacro("TestConvergence");

  /** Get the number of parameters from the cost function */
  const unsigned int numberOfParameters = this->GetScaledCostFunction()->GetNumberOfParameters();

  /** Some casts/aliases: */
  const unsigned int N = numberOfParameters;

  /** Check if the maximum number of iterations will not be exceeded in the following iteration */
  if ((this->GetCurrentIteration() + 1) >= this->GetMaximumNumberOfIterations())
  {
    this->m_StopCondition = MaximumNumberOfIterations;
    return true;
  }

  /** Check if the step was not too large:
   * if ( sigma * sqrt(C[i,i]) > PositionToleranceMax*sigma0   for any i ) */
  const double tolxmax = this->m_PositionToleranceMax * this->m_InitialSigma;
  bool         stepTooLarge = false;
  if (this->GetUseCovarianceMatrixAdaptation())
  {
    for (unsigned int i = 0; i < N; ++i)
    {
      const double sqrtCii = std::sqrt(this->m_C[i][i]);
      const double stepsize = this->m_CurrentSigma * sqrtCii;
      if (stepsize > tolxmax)
      {
        stepTooLarge = true;
        break;
      }
    } // end for i
  }
  else
  {
    const double sqrtCii = 1.0;
    const double stepsize = this->m_CurrentSigma * sqrtCii;
    if (stepsize > tolxmax)
    {
      stepTooLarge = true;
    }
  } // end else: if no covariance matrix adaptation
  if (stepTooLarge)
  {
    this->m_StopCondition = PositionToleranceMax;
    return true;
  }

  /** Check for zero steplength (should never happen):
   * if ( sigma * D[i] <= 0  for all i  ) */
  bool zeroStep = false;
  if (this->GetUseCovarianceMatrixAdaptation())
  {
    if ((this->m_CurrentSigma * this->m_D.diagonal().max_value()) <= 0.0)
    {
      zeroStep = true;
    }
  }
  else
  {
    if (this->m_CurrentSigma <= 0.0)
    {
      zeroStep = true;
    }
  }
  if (zeroStep)
  {
    this->m_StopCondition = ZeroStepLength;
    return true;
  }

  /** The very first convergence check can not test for everything yet */
  if (firstCheck)
  {
    return false;
  }

  /** Check if the step was not too small:
   * if ( sigma * max( abs(p_c[i]), sqrt(C[i,i]) ) < PositionToleranceMin*sigma0  for all i ) */
  const double tolxmin = this->m_PositionToleranceMin * this->m_InitialSigma;
  bool         stepTooSmall = true;
  for (unsigned int i = 0; i < N; ++i)
  {
    const double pci = std::abs(this->m_EvolutionPath[i]);
    double       sqrtCii = 1.0;
    if (this->m_UseCovarianceMatrixAdaptation)
    {
      sqrtCii = std::sqrt(this->m_C[i][i]);
    }
    const double stepsize = this->m_CurrentSigma * std::max(pci, sqrtCii);
    if (stepsize > tolxmin)
    {
      stepTooSmall = false;
      break;
    }
  }
  if (stepTooSmall)
  {
    this->m_StopCondition = PositionToleranceMin;
    return true;
  }

  /** Check if the best function value changes over iterations */
  if (this->m_MeasureHistory.size() > 10)
  {
    const MeasureType maxhist = *max_element(this->m_MeasureHistory.begin(), this->m_MeasureHistory.end());
    const MeasureType minhist = *min_element(this->m_MeasureHistory.begin(), this->m_MeasureHistory.end());
    if ((maxhist - minhist) < this->m_ValueTolerance)
    {
      this->m_StopCondition = ValueTolerance;
      return true;
    }
  }

  return false;

} // end TestConvergence


} // end namespace itk